Can the ViewBag name be the same as the Model property name in a DropDownList?

半腔热情 提交于 2019-11-25 21:55:36

问题


I am working on an ASP.NET MVC-4 web application. I\'m defining the following inside my action method to build a SelectList:

ViewBag.CustomerID = new SelectList(db.CustomerSyncs, \"CustomerID\", \"Name\");

Then I am rendering my DropDownListFor as follow inside my View:

 @Html.DropDownListFor(model => model.CustomerID, (SelectList)ViewBag.CustomerID, \"please select\")

As shown I am naming the ViewBag property to be equal to the Model property name which is CustomerID. From my own testing, defining the same name didn\'t cause any problem or conflict but should I avoid this ?


回答1:


You should not use the same name for the model property and the ViewBag property (and ideally you should not be using ViewBag at all, but rather a view model with a IEnumerable<SelectListItem> property).

When using @Html.DropDownListFor(m => m.CustomerId, ....) the first "Please Select" option will always be selected even if the value of the model property has been set and matches one of the options. The reason is that the method first generates a new IEnumerable<SelectListItem> based on the one you have supplied in order to set the value of the Selected property. In order to set the Selected property, it reads the value of CustomerID from ViewData, and the first one it finds is "IEnumerable<SelectListItem>" (not the value of the model property) and cannot match that string with any of your options, so the first option is selected (because something has to be).

When using @Html.DropDownList("CustomerId", ....), no data-val-* attributes will be generated and you will not get any client side validation

Refer this DotNetFiddle showing a comparison of possible use cases. Only by using different names for the model property and the ViewBag property will it all work correctly.




回答2:


There is not harm to use it. You will not get any error. but best practice is to bind model property.



来源:https://stackoverflow.com/questions/37161202/can-the-viewbag-name-be-the-same-as-the-model-property-name-in-a-dropdownlist

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