asp.net mvc 3 pre-select Html.DropDownListFor not working in nerd dinner

后端 未结 5 2069
一向
一向 2020-12-31 07:19

Learning about dropdown lists, Im trying to add a RSVP create page for nerddinner as in Scott Gu\'s blog with a Html.DropDownListFor listing available dinners.

I ca

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 08:04

    Html.DropDownList accepts int properties, DropDownListFor too, but you have to be careful what you are doing. I examined the SelectExtensions.cs from ASP.NET MVC 3 and found this:

    When you use DropDownList("XyField", "default") to create a DropDown, then you must place the select list into ViewBag.XyField and DropDownList() handles this correctly.

    When you use DropDownListFor(m=>m.XyField, ... ), you can pass the select list explictly, like this: DropDownListFor(m=>m.XyField, ViewBag.XyFieldList as IEnumerable)

    When you do this, this following happen:

    • The second parameter of DropDownListFor(...) will be used as source for the options
    • If there is a ModelState entry for "XyField", this will be used as the model value
    • If there is no model state AND Html.ViewData.Eval("XyField") returns not null, this value will be used as the model value.
    • If the found model value is not null, it will be converted to a string, using CultureInfo.CurrentCulture, and this value is compared with your SelectListItem values to preselect the list options.

    Attention here: if you stored your select list in ViewBag.XyField, it will be found before the model is accessed. The don't want to compare "selectList.ToString()" with "selectList[i].Value" to preselect your options. Store your selection list in another place!

    The funny thing is, you CAN use DropDownListFor with an implicit select list, in the same way as you expect it from DropDownList(). In this case, you will even store your list in ViewBag.XyField. To make this work, you simply have to call the helper with null as second parameter: DropDownListFor(m=>m.XyField, null)

    Then, the select list is pulled from ViewBag.XyField and step 3 in the list above is skipped. So, if XyField is in the model state, this will take precedence before your own Selected properties in the select list, but otherwise, the select list will be used "as is".

    Greetings Rolf

提交回复
热议问题