ViewBag 名称可以与 DropDownList 中的 Model 属性名称相同吗? [英] Can the ViewBag name be the same as the Model property name in a DropDownList?
问题描述
我正在开发一个 ASP.NET MVC-4 Web 应用程序.我在我的操作方法中定义了以下内容来构建一个 SelectList
:
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");
然后我在我的 View
中渲染我的 DropDownListFor
如下:
Then I am rendering my DropDownListFor
as follow inside my View
:
@Html.DropDownListFor(model => model.CustomerID, (SelectList)ViewBag.CustomerID, "please select")
如图所示,我将 ViewBag
属性命名为等于 Model
属性名称,即 CustomerID
.根据我自己的测试,定义相同的名称不会导致任何问题或冲突,但我应该避免这种情况吗?
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 ?
推荐答案
你不应该对模型属性和 ViewBag
属性使用相同的名称(理想情况下你不应该使用 ViewBag
,而是一个带有 IEnumerable
属性的视图模型).
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).
当使用 @Html.DropDownListFor(m => m.CustomerId, ....)
时,第一个 请选择"
选项将始终被选中,即使模型属性的值已设置并匹配选项之一.原因是该方法首先根据您提供的值生成一个新的 IEnumerable
,以便设置 Selected
属性的值.为了设置Selected
属性,它从ViewData
中读取CustomerID
的值,找到的第一个是"IEnumerable<SelectListItem>"
(不是模型属性的值)并且无法将该字符串与您的任何选项匹配,因此选择了第一个选项(因为必须有某些内容).
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).
当使用 @Html.DropDownList("CustomerId", ....)
时,不会生成 data-val-*
属性,你不会得到任何客户端验证
When using @Html.DropDownList("CustomerId", ....)
, no data-val-*
attributes will be generated and you will not get any client side validation
请参阅 此 DotNetFiddle,其中显示了可能使用案例的比较.只有为模型属性和 ViewBag
属性使用不同的名称,它才能正常工作.
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.
这篇关于ViewBag 名称可以与 DropDownList 中的 Model 属性名称相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!