Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc MVC RadioButton为每个元素输出相同的ID_Asp.net Mvc_Asp.net Mvc 4_Radio Button - Fatal编程技术网

Asp.net mvc MVC RadioButton为每个元素输出相同的ID

Asp.net mvc MVC RadioButton为每个元素输出相同的ID,asp.net-mvc,asp.net-mvc-4,radio-button,Asp.net Mvc,Asp.net Mvc 4,Radio Button,我有一个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 =

我有一个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>

@RadioButton(x=>x.Vote,1,新的{@class=“rdbn”})
@RadioButton(x=>x.Vote,2,新的{@class=“rdbn”})
@RadioButton(x=>x.Vote,3,新的{@class=“rdbn”})
运行应用程序时,输出为:

<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>


问题是,
输入
元素的ID每次都是相同的。我试图在这些单选按钮上运行一些jquery,但是很明显,如果每个元素的ID都相同,我就做不到。是否有一种简单的方法可以使ID每次都是唯一的,而不必使用HTML属性手动指定它?

为了避免每次都必须设置ID属性,您可以创建一个类似于以下内容的扩展方法(未测试):

public static MvcHtmlString RadioButtonListFor
(此HtmlHelper HtmlHelper,表达式,
IEnumerable值、IDictionary属性)
{
var builder=新的StringBuilder();
foreach(值中的var值)
{
//基于单选按钮值创建唯一id
如果(!htmlAttributes.ContainsKey(“id”))
Add(“id”,string.Format(“{0}{1}”,htmlHelper.IdFor(表达式),value.ToString());
Append(htmlhelp.RadioButtonFor(表达式、值、htmlAttributes));
}
返回新的MvcHtmlString(builder.ToString());
}
然后您可以在视图中使用此扩展:

<div class="vote">
    @Html.RadioButtonListFor(x => x.Vote, new[] {1, 2, 3},  new { @class = "rdbn" })
</div>

@RadioButtonListFor(x=>x.Vote,new[]{1,2,3},new{@class=“rdbn”})

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

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

+1.反对否决票。当解决方案如此简单时,不需要过分复杂(或者手动编写html并自行设置ID,而不是使用帮助器)。这完全违背了这一点。表单上具有相同的id是无效的HTML。
$("#idOfRadioButton").find(":radio[value=1]")