会不会有什么冲突,如果我指定viewBag名称等于内部@ Html.DropDownListFor模型属性名 [英] Will there be any conflict if i specify the viewBag name to be equal to the model property name inside @Html.DropDownListFor
问题描述
我工作的一个asp.net MVC-4的Web应用程序。我定义我的操作方法来构建一个选择列表内的以下内容: -
I am working on an asp.net mvc-4 web application. and i define the following inside my action method to build a select list:-
ViewBag.CustomerID = new SelectList(db.CustomerSyncs, "CustomerID", "Name");
那么我渲染我的 DropDownListFor
如按照我的看法里: -
Then i am rendering my DropDownListFor
as follow inside my view:-
@Html.DropDownListFor(model=>model.CustomerID,(SelectList)ViewBag.CustomerID, "please select")
现在如我正在命名viewbag等于这是客户ID
模型属性名。现在从我自己的测试中定义同名没有造成任何问题或冲突..但不知道我应该避免这种情况?
now as shown i am naming the viewbag to be equal to the model property name which is CustomerID
. now from my own test defining the same name did not cause any problem or conflict.. but not sure if i should avoid this ?
感谢
推荐答案
您不应该为模型属性和 ViewBag
属性中使用相同的名称(理想情况下,你应该不使用 ViewBag
可言,而是用的IEnumerable℃的视图模型; SelectListItem方式>
属性)
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 = GT; m.CustomerId,....)
第一个请选择即使模型属性的值已设置且相匹配的选项之一将始终选择code>选项。其原因是,该方法首先生成一个新的
的IEnumerable&LT; SelectListItem&GT;
根据您以设置所选的价值提供一个
属性。为了将选
属性,它会读取客户id的值
从的ViewData
,它找到的第一个是的IEnumerable&LT; SelectListItem&gt;中
(模型属性不是值),不能与任何该字符串匹配选项,所以第一个选项被选中(因为有些事情是)。
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(客户编号,....)
,没有数据-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名称等于内部@ Html.DropDownListFor模型属性名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!