我有一个EditorTemplate,里面有一组Radio Buttons。
<div class="vote">
@Html.RadioButtonFor(x => x.Vote, 1, new { @class = "rdbn" })
@Html.RadioButtonFor(x => x.Vote, 2, new { @class = "rdbn" })
@Html.RadioButtonFor(x => x.Vote, 3, new { @class = "rdbn" })
</div>
当我运行应用程序时,输出为:
<div class="vote">
<input id="Reviews_0__Vote" type="radio" class="myCssClass" value="1" name="Reviews[0].Vote">
<input id="Reviews_0__Vote" type="radio" class="myCssClass" value="2" name="Reviews[0].Vote">
<input id="Reviews_0__Vote" type="radio" class="myCssClass" value="3" name="Reviews[0].Vote">
</div>
<div class="vote">
<input id="Reviews_1__Vote" type="radio" class="myCssClass" value="1" name="Reviews[1].Vote">
<input id="Reviews_1__Vote" type="radio" class="myCssClass" value="2" name="Reviews[1].Vote">
<input id="Reviews_1__Vote" type="radio" class="myCssClass" value="3" name="Reviews[1].Vote">
</div>
问题是每次input
元素的ID都是相同的。我试图在这些单选按钮上运行一些jquery但显然我不能解释每个元素的ID是否相同。是否有一种简单的方法可以使ID每次都不唯一,而无需使用HTML属性手动指定它?
答案 0 :(得分:2)
为了节省您每次都必须设置id属性,您可以创建类似于以下(未经测试)的扩展方法:
public static MvcHtmlString RadioButtonListFor<TModel, TProperty>
(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression,
IEnumerable<object> values, IDictionary<string, object> htmlAttributes)
{
var builder = new StringBuilder();
foreach (var value in values)
{
//Create a unique id based on the radio button value
if (!htmlAttributes.ContainsKey("id"))
htmlAttributes.Add("id", string.Format("{0}_{1}", htmlHelper.IdFor(expression), value.ToString()));
builder.Append(htmlHelper.RadioButtonFor(expression, value, htmlAttributes));
}
return new MvcHtmlString(builder.ToString());
}
然后您可以在视图中使用此扩展程序:
<div class="vote">
@Html.RadioButtonListFor(x => x.Vote, new[] {1, 2, 3}, new { @class = "rdbn" })
</div>
答案 1 :(得分:0)
您可以使用jQuery按值查找各个单选按钮,而不是通过ID:
$("#idOfRadioButton").find(":radio[value=1]")