.NET MVC SelectList’s Selected Value Does Not Get Set in the View


Programming in Ruby tutorials and examples

.NET MVC SelectList’s Selected Value Does Not Get Set in the View

MaxCDN Content Delivery Network

If you have used .NET MVC you may have found that the selected value property that is set on the constructor of the SelectList does not set the selected value of the drop down list in a strongly typed view. Below is an overview of how the model, view and controller were set up and how I overcame this issue.

I setup a strongly typed view of a type of Page from my LINQ to SQL model (I am building a MVC CMS and this controller and view were setup in order to edit a page).

PageModel  ScreenGrabEditpage

I passed in a select list to the view data and I set the current pages ParentId to be the selected option in the parent pages dropdown list. But when the page loaded the dropdown just defaulted to the first option rather than the one set on the SelectList.

        
  [AcceptVerbs(HttpVerbs.Get)]
  public ActionResult EditPage(int id)
  {
    Page page = iPageData.SelectPageById(id);
    ViewData["PageCreatedByUserId"] = UserList();
    ViewData["PageParentId"] = new SelectList(iPageData.SelectTopLevelMenuItems(),"PageId", "PageTitle", page.PageParentId);
    ViewData.Model = page;
    return View();
  }

In my View the dropdown list’s name was set to the name of my LINQ 2 SQL model as was the key in the ViewData.

                
  <%=Html.DropDownList("PageParentId", (IEnumerable) ViewData["PageParentId"],"***** No Parent Page *****")%>

In MVC if the view is strongly typed the selectlist’s selected option will be overridden and the selected option property set on the constructor will never reach the view and the first option in the dropdown will be selected instead (why is still a bit of a mystery). To overcome this issue all that needs to be done is to rename the DropDownList in the view and also the name of the ViewData’s key in the controller to something other than the name set in the model , and the selected option will then reach the view. Unfortunately when posting the form you will have to access the selected option’s value from the FormCollection rather than a strongly typed object which is a little annoying.