ASP.NET MVC - Html.DropDownList - Value not set via ViewData.Model

前端 未结 7 1152
Happy的楠姐
Happy的楠姐 2020-12-14 09:24

Have just started playing with ASP.NET MVC and have stumbled over the following situation. It feels a lot like a bug but if its not, an explanation would be appreciated :)<

7条回答
  •  感情败类
    2020-12-14 09:58

    Actually, you just have to pass in null for the Html.DropDownList().
    I was having the same exact problem, and used the Reflector to look at the MVC Source Code.

    In the System.Web.Mvc.Extensions.SelectExtensions class's SelectInternal() method, it checks whether the selectList parameter is null or not. If it is passed in as null, it looks up the SelectList properly.

    Here is the "Code-behind".

    ViewData["MyDropDown"] = new SelectList(selectListItems,
                                 "Value",
                                 "Text",
                                 selectedValue.ToString()
                             );
    

    Here is the HTML view code.

    <%= Html.DropDownList("MyDropDown", null,
            "** Please Select **",
            new { @class = "my-select-css-class" }
        ) %>
    

    Note: I'm using ASP.NET MVC 2.0 (Beta Version).

    UPDATE NOTE: January 31st 2012

    After extensively using ASP.NET MVC for the past 3 years, I prefer using additionalViewData from the Html.EditorFor() method more.

    Pass in your [List Items] as an anonymous object with the same property name as the Model's property into the Html.EditorFor() method.

    <%= Html.EditorFor(
        m => m.MyPropertyName,
        new { MyPropertyName = Model.ListItemsForMyPropertyName }
    ) %>
    

    If you want more details, please refer to my answer in another thread here.

提交回复
热议问题