Search code examples
razorhtml-helperselectlistselectlistitem

How to populate SelectList with States in Controller Create Action


I am trying to use the code from MS tutorial NerdDinner to populate a pulldown with states, including whatever already exists (for Edit ActionResult).

Here is what was used for Phone Countries in NerdDinner:

//ViewData["Countries"] = new SelectList(PhoneValidator.AllCountries, dinner.Country);

I have all the States, I just added a few to test. Doesn't work for this helper:

public ActionResult Create()
{

    Operation operation = new Operation();

    ViewData["States"] = new SelectList(
        new List<SelectListItem>
        {           
             new SelectListItem{ Text="Ohio", Value="OH"},
            new SelectListItem{ Text="Oklahoma", Value="OK"},
            new SelectListItem { Text="Oregon", Value="OR"},
            new SelectListItem{ Text="Pennsylvania", Value="PA"},
            new SelectListItem{ Text="Rhode Island", Value="RI"}
        }, operation.State);


    return View(operation);

}

Here is the helper in the Create View (would be the same as Edit View):

@Html.DropDownList("States", ViewData["States"] as SelectList))

Solution

  • You have a number of issues. Firstly you build a collection of SelectListItem (which is all the DropDownList requires) but then try to make a SelectList from it. Apart from being pointless extra overhead, your not specifying the dataValueField and dataTextField parameters so your generating a whole lot of options which would look like

    <option>System.Web.Mvc.SelectListItem</option>
    

    and the second parameter where you attempt to set the selected option will also not work (unless operation.State was typeof SelectListItem)

    Secondly, you cannot use the same name for the property your binding to and the SelectList. Your SelectList should be named (say) StateList

    Finally, your not actually binding to anything. Your model contains a property named State, not States. Always use the strongly typed html helpers.

    Your code should be

    public ActionResult Create()
    {
        Operation operation = new Operation();
        ViewData["StateList"] = new List<SelectListItem>()
        {           
            new SelectListItem{ Text="Ohio", Value="OH"},
            new SelectListItem{ Text="Oklahoma", Value="OK"},
            ....
        };
        return View(operation);
    }
    

    and in the view

    @Html.DropDownListFor(m => m.State, (IEnumerable<SelectListItem>)ViewData["StateList"])
    

    In your case the first option ("Ohio") will be selected because the value of State is null and does not match one of your options. If you were to use operation.State = "OR"; in the controller, then the 3rd option ("Oregon") will be selected when you first render the view.