【问题标题】:MVC RadioButtonFor outputs same ID for every elementMVC RadioButtonFor 为每个元素输出相同的 ID
【发布时间】:2013-05-29 04:01:19
【问题描述】:

我有一个 EditorTemplate,其中包含一组单选按钮。

<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 属性手动指定它?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 radio-button


    【解决方案1】:

    为了避免每次都设置 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>
    

    【讨论】:

      【解决方案2】:

      您可以使用 jQuery 按值查找单个单选按钮,而不是按 ID:

      $("#idOfRadioButton").find(":radio[value=1]")
      

      【讨论】:

      • +1 反对反对票。当解决方案如此简单时,无需过于复杂(或手动编写html并自己设置ID而不是使用帮助程序)。
      • 这完全违背了重点。表单上的 id 相同是无效的 HTML。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多