开发者

dropdown problem

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?


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"})%>


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.


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;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜