ViewBag名称可以与DropDownList中的Model属性名称相同吗? [英] Can the ViewBag name be the same as the Model property name in a DropDownList?

查看:66
本文介绍了ViewBag名称可以与DropDownList中的Model属性名称相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究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:

 @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 ?

推荐答案

您不应对model属性和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 => m.CustomerId, ....)时,即使已设置模型属性的值并与其中一个选项匹配,也会始终选择第一个"Please Select"选项.原因是该方法首先根据您提供的值生成一个新的IEnumerable<SelectListItem>,以设置Selected属性的值.为了设置Selected属性,它从ViewData读取CustomerID的值,并且找到的第一个是"IEnumerable<SelectListItem>"(不是model属性的值),并且不能将该字符串与以下任何一个匹配您的选项,因此选择了第一个选项(因为必须进行选择).

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 ,以比较可能的用例.只有对model属性和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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆