[英]How to add Class to SelectListItem in ASP.NET MVC5 Razor Syntax?
I created a select input field using the Razor. 我使用剃刀创建了一个选择输入字段。 Given below is the code: 下面是代码:
@Html.DropDownList("selectOption", new[] {
new SelectListItem()
{
Text ="Option 1" , Value = "1"
},
new SelectListItem()
{
Text = "Option 2" , Value = "2"
},
new SelectListItem()
{
Text = "Option 3" , Value = "3"
}
},
"Choose an Option...",
new {@class = "form-control" })
I am aware of adding custom class to select input field but how do I add custom class to each of the select options? 我知道要添加自定义类来选择输入字段,但是如何将自定义类添加到每个选择选项中呢? Is it even possible using razor syntax? 甚至可以使用razor语法吗?
I can get the results by using jQuery but I want to know whether there exists method using only razor. 我可以使用jQuery获得结果,但我想知道是否存在仅使用剃刀的方法。
You can't do it with the built in methods. 您无法使用内置方法来做到这一点。 You could create your own extension method or helper , however it would be much easier to just create the control yourself using HTML: 您可以创建自己的扩展方法或帮助程序 ,但是使用HTML自己创建控件会容易得多:
<select class="form-control" id="selectOption" name="selectOption">
<option value="">Choose an Option...</option>
<option class="some-class-1" value="1">Option 1</option>
<option class="some-class-2" value="2">Option 2</option>
<option class="some-class-3" value="3">Option 3</option>
</select>
It even makes it more readable (in my opinion). 它甚至使它更具可读性(我认为)。 You shouldn't feel like you have to use the helpers for everything. 您不应该觉得必须使用助手来完成所有事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.