tags:

views:

45

answers:

3

I got this line of code:

<%=Html.DropDownList("Status",(SelectListItem[])ViewData["statusList"], new {@style = "width: 190px"})%>

The dropdown is always populated with the data from ViewData which is good but i want to be selected the value corresponding to the Model.Status property. What am i doing wrong?

A: 

It doesn't appear that you are setting the value to status. You've got "Status" as the name, but, at least in that line, Model.Status is not set anywhere.

taylonr
Model.Status has a value of course, let's say 3.ViewData["statusList"] is for example an array like {1,"aaa"} {2,"bbb"} {3,"ccc"} {4,"ddd"}.Then i create the dropdown which is populated with those 4 values but is selected the first not the one with value=3
bogus
Right, what I'm saying is, in the View code, I don't think you're telling the dropdown what value to select. Off the top of my head, I think you need something like Dropdown("Status", ViewData["statusList"], Model.Status) to tell it what value to select.
taylonr
Oh, my bad, I forgot you can specify the selectedItem in the SelectList.. can you paste that code? Perhaps the problem is in your controller and not your view.
taylonr
+2  A: 

When you create the SelectList (this is done in the Model or Controller (not recommended but it'd be fine), NOT in the view) you can just pass the selected item in the constructor and it will take care for the rest:

ViewData["statusList"] = new SelectList(yourList, selectedItem);

Then you don't have to cast the list from the ViewData to a SelectListItem but to a SelectList. This is the only line that should appear in your view.

<%=Html.DropDownList("Status",(SelectList)ViewData["statusList"], new {@style = "width: 190px"})%>
Davide Vosti
A: 

I did this in the view:

<%SelectListItem[] statusVals=(SelectListItem[])ViewData["statusList"];%>
         <%foreach(SelectListItem statusVal in statusVals){%> 
            <% if(statusVal.Value==Model.Status.ToString())
                           statusVal.Selected=true;%>
            <%} %>
         <%=Html.DropDownList("Status", statusVals, new { @style = "width: 190px" })%>

The statusVals is created well but when i reach the dropdown line all items have Selected=false;

bogus
I've never modified my list in the view. Perhaps a better way is to pick the selected item when you create your list, not in the view. This thread: http://forums.asp.net/t/1382564.aspx seems to have a similar issue. The "solution" there was to pick @ creation
taylonr
You are doing the wrong way. The select list has to be created in the Model (or in the controller will be good anyway). I modified my reply so you should understand better. In the view you should never ever put any particular logic...
Davide Vosti
I renamed the dropdown and i make the assignments myself, it was stupid anyway to add logic in the view
bogus