MVC3 选择列表项。是否可以用自定义 html 属性来装饰它?
如果我有这样的东西:
@{
var cats = GetCategories();
var selectList = from c in cats
select new SelectListItem
{
Selected = (c.Id == Model.SessionCategory.Id),
Text = c.Name,
Value = c.Id.ToString(),
};
}
@Html.DropDownList("categories", selectList)
标记将是这样的:
<select id="categories" name="categories">
<option value="1">Category1</option>
<option value="2">Category2</option>
<option selected="selected" value="3">Category3</option>
</select>
现在的问题是:
是否可以向每个 标记添加其他属性? 我的意思是来自 Razor 模板。没有 jQuery 解决方法吗?
if I have something like this:
@{
var cats = GetCategories();
var selectList = from c in cats
select new SelectListItem
{
Selected = (c.Id == Model.SessionCategory.Id),
Text = c.Name,
Value = c.Id.ToString(),
};
}
@Html.DropDownList("categories", selectList)
The markup would be like this:
<select id="categories" name="categories">
<option value="1">Category1</option>
<option value="2">Category2</option>
<option selected="selected" value="3">Category3</option>
</select>
And now, the question is:
Is it possible to add additional attributes to each <option>
tag?
I mean from the Razor template. Without jQuery workarounds?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为最实用的解决方案是一些 jQuery 或者类似的东西..
你显然可以根据需要添加属性...
I think the most practical solution would be some jQuery or maybe something like this..
you could obviously add in attributes as needed...
默认情况下,否。
SelectListItem
不包含任何可添加属性的其他属性。但是,您可以创建自己的DropDownList
方法或DropDownListFor
并使用自定义创建自己的
添加您自己的属性。ListItemToOption
SelectListItem但这可能有点过分了。
By default, no. The
SelectListItem
does not contain any additional properties to add your attributes to. However, you could create your ownDropDownList
method orDropDownListFor
and create your ownListItemToOption
with a customSelectListItem
to add your own attributes.But it's probably overkill.
我是这样做的:
我创建了自己的 DropDownListFor:
然后我的
SelectListItem List
创建如下:Here's how I did it:
I created my own DropDownListFor:
Then my
SelectListItem List
is created like this: