DropDownListFor Not Displaying/Persisting Null for First Choice in List

喜欢而已 提交于 2019-12-11 07:44:12

问题


I have an MVC app via SharpArch. In the view I have:

 Html.DropDownListFor(x => x.Location, 
     new SelectList(Model.PossibleLocations, "Id", "Address"), 
     "-- No Location --")

I have 2 issues.

  1. The Dropdown is not getting updated when the view gets bound to the model.
  2. A selection gets persisted correctly except when I try the top "no location".

I was able to take care of the first point by changing x.Location to x.Location.Id but then I had other issues.

I can find plenty of examples for DropDownList, but none in which saving a null is shown.

Any help is appreciated.

Thanks

UPDATE:

I just upgraded Resharper (a minor update) and am getting prompted to fill it DropDownListFor. Why would that make a difference? It was working enough to bind and now it doesn't work at all.


回答1:


You could always insert the "empty" SelectListItem into your PossibleLocations collection before passing to the View and check for that "empty" value (0 for instance) when the form is posted

model.PossibleLocations.Insert(0, 
    new SelectListItem() { Text = "-- No Location --", Value = "0" };



回答2:


Try "flattening" your model class so that LocationId is the actual value you're binding to (i.e. add a "LocationId" property to your model, and create a DropDownList for x => x.LocationId).



来源:https://stackoverflow.com/questions/5986042/dropdownlistfor-not-displaying-persisting-null-for-first-choice-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!