带有自定义参数的 Html.DropDownListFor()
例如
<select id="Country" name="Country">
<option data-domain="AN" value="1">Andorra</option>
<option data-domain="UI" value="2">United Arab Emirates</option>
<option data-domain="AF" value="3">Afghanistan</option>
选项具有数据域属性,我可以像这样使用它
@Html.DropDownListFor(m => m.Country, Model.CountryList)
Model.CountryList
是国家/地区变量的数组
class Country
{
public String Text { get; set; }
public String Value { get; set; }
public String Domain { get; set; }
}
我想在 HTML 帮助程序中添加扩展方法来生成选择和选项, 谁能给出解决方案
I want to add extension method in HTML helpers for generating select and options like this
<select id="Country" name="Country">
<option data-domain="AN" value="1">Andorra</option>
<option data-domain="UI" value="2">United Arab Emirates</option>
<option data-domain="AF" value="3">Afghanistan</option>
the options have a data-domain attribute, and I can use it like this
@Html.DropDownListFor(m => m.Country, Model.CountryList)
the Model.CountryList
is an arrayh of Country valiables
class Country
{
public String Text { get; set; }
public String Value { get; set; }
public String Domain { get; set; }
}
please can anyone give a solution
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以借助自定义帮助程序方法构建
CustomDropdownListFor
,如下所示:自定义帮助程序方法:
查看 (剃须刀):
You can build your
CustomDropdownListFor
with the help of a custom helper method as shown below:Custom Helper Method:
View (Razor):
标准
DropDownList/DropDownListFor
帮助程序不支持此功能。如果您需要此类功能,则必须从头开始编写自定义 HTML 帮助程序。您可以查看此示例。还有另一个。The standard
DropDownList/DropDownListFor
helpers do not support this. You will have to write a custom HTML helper from scratch if you need such functionality. You may checkout this example. And another one.方法:
调用:
Method:
Call:
对 Murat 的答案进行轻微重构:
使用 SelectListItem 自己的属性,仅添加是 Class,不要对 val 属性进行硬编码,因为它们已经在模型元数据上读取
Slight refactor of Murat's answer:
Uses SelectListItem's own properties, only addition is Class, do not hardcode val attributes as they are already read on the model metadata