tags:

views:

123

answers:

2

For some reason my drop down list is not retaining it's selected value - I know I am missing something simple here. Thanks for any comments!

Controllers

    public ActionResult Test()
    {
        ViewData["MonitoringType"] = new SelectList(myModel.GetMonitoringType(), "Category", "Category");
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Test(FormCollection formValues)
    {
        ViewData["MonitoringType"] = new SelectList(myModel.GetMonitoringType(), "Category", "Category", formValues["MonitoringType"]);
        return View();
    }

And View:

This doesn't work

<%= Html.DropDownList("MonitoringType", (SelectList)ViewData["MonitoringType"],new {style = "width: 300px;"})%>

This works

<%= Html.DropDownList("MonitoringType")%>
+2  A: 

Hi!

quote from controller:

    var projects = from project in DB.Projects
                   orderby project.Name
                   select new { project.Id, project.FullName };
    ViewData["ProjectId"] = new SelectList(projects, "Id", "FullName", selectedProjectId);

quote from page:

<%= Html.DropDownList("ProjectId", "-- All Projects --")%>
Dmitry44
Thanks for the comment - I guess I should have made it a bit more explicit "Category" is distinct and is both the value and the text. And really where it is failing is the (SelectList)ViewData["MonitoringType"]
Eric Ness
A: 

Take a look at my answer to a similar question. It appears there is a bug in the DropDownList extension method when using methods other than DropDownList(name).

http://stackoverflow.com/questions/589935/html-dropdownlist-in-asp-net-mvc-rc-refresh-not-pre-selecting-item

Troy