We help IT Professionals succeed at work.

ASP.Net MVC 2 setting a DropDownListFor item

hijiki7777
hijiki7777 asked
on
I am new to MVC and I am starting at version 2. I am populating a View with a row of data that contains an Id field (Status). This Id field is bound to a list of Status strings displayed in a drop down list. In my controller I populate a SelectList collection in which the current Status is correctly selected (I checked this). However the View always selects the first item on the list regardless. So what is wrong with this?
<div class="editor-field">
            <%: Html.DropDownListFor(model => model.Status, ViewData["Status"] as IEnumerable<SelectListItem>)%>
            <%: Html.ValidationMessageFor(model => model.Status) %>
        </div>

Open in new window

Comment
Watch Question

Top Expert 2009

Commented:
Please see the link below to see how exactly to set the selected item on a dropdownlist:

http://stackoverflow.com/questions/624828/asp-net-mvc-html-dropdownlist-selectedvalue

Arun
I think it's because you have used a property on the model called status and an item in the viewdata called status. Personally I would advise you to rely on the model alone and not use ViewData in your views.

therefore change your view to

<%: Html.DropDownListFor(model => model.Status, Model.StatusSelectList)%>

and add a

public IEnumerable<SelectListItem> StatusSelectList {get.......

property to your model.


Author

Commented:
Spot on.
I think I should use the View Model from now on.
If you look at most ASP.NET MVC best practice recommendations they advise using the Model rather than using magic strings which are error prone.