我使用@ Html.RadioButtonFor()html属性从集合中生成单选按钮:
@foreach (var radioItem in (IEnumerable<MyMatrimony.Models.tblGenderMaster>)ViewBag.GenderId)
{
@Html.RadioButtonFor(model => model.GenderId, radioItem.Id, new { htmlAttributes = new { @class = "form-control", @id = "radio" + Guid.NewGuid().ToString() } })
@radioItem.Gender
}
单选按钮呈现正常,但在google chrome的控制台中,它会抛出以下错误:
[DOM] Found 2 elements with non-unique id #GenderId:
<input data-val="true" data-val-number="The field Gender must be a number." data-val-required="The Gender field is required." htmlattributes="{ class = form-control, id = radio95083401-4ebf-4ee4-b402-3a9018770a60 }" id="GenderId" name="GenderId" type="radio" value="1">
<input htmlattributes="{ class = form-control, id = radio603703f0-8319-49ed-b6eb-82018c9a51e0 }" id="GenderId" name="GenderId" type="radio" value="2">
虽然我在htmlattributes中指定了唯一的ID,但它会在输入元素中自动添加单独的Id字段,我认为这会导致错误。
请帮我解决这个错误。 提前谢谢。
答案 0 :(得分:1)
通过将@ HTML.RadioButtonFor()html帮助程序的htmlAttributes更改为匿名对象来解决此问题:
@Html.RadioButtonFor(model => model.GenderId, radioItem.Id, new { @id = "radio" + Guid.NewGuid().ToString() })
看起来参数本身需要直接的htmlAttributes,因此我们不需要明确指定它。
Html.RadioButtonFor(model =&gt; property,object value,object htmlAttributes)