Question

I have the following code which is meant to populate a dropdown with a bunch of integer values and make the currently selected value (in this case, 13) be the selected item.

I've used the same technique but for string values and it works great, remembering each time when I get to the view what the current value is.

In controller:

var x = new[] { 1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15 };

ViewData["Field"] = new SelectList(x, 13);

In view:

<%=Html.DropDownList("Field", (IEnumerable<SelectListItem>)ViewData["Field"])%>

When I debug and watch the ViewData["Field"] object, it does have a selectedValue of 13 and so it must be reaching the View but getting ignored there as all I see on the page is a dropdown with the values 1 to 15, but with 1 showing (none selected so shows the first one)

Is this a bug or am I doing something really stupid?

Thanks

Graeme

Was it helpful?

Solution

I seem to recall that it doesn't actually use the Selected property of the SelectList element. I usually have one ViewData item be the select list and another be the selected value.

Controller:

var x = new[] { 1, 2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
ViewData["Fields"] = new SelectList(x);
ViewData["Field"] = 13;

View

<%= Html.DropDownList("Field", (IEnumerable<SelectListItem>)ViewData["Fields"] ) %>

OTHER TIPS

This was happening to me! I was pulling my hair out for hours, but I eventually figured it out. In my case I was creating a drop-down list like this:

<%= Html.DropDownList("bookId", Model.ProductMenu, new { onchange = "goToBook();" })%>

And it was not printing the selected option. But the dropdown right next to it was working fine:

<%= Html.DropDownList("segmentIndex", Model.SegmentMenu, new { onchange = "goToSegment();" })%>

They were being generated the exact same way in the controller, and the debugger would always show the properly selected value as the view was returned. So what the heck?

The difference was in the view itself. "bookId" in my app happens to be a route/querystring value and segmentIndex is not. Simply changing the name "bookId" in the view to "bookIdBLAH" fixed it!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top