通过MVC模型变量添加在单选按钮的新属性
问题描述:
我有MVC类和变量之一,被宣布为:通过MVC模型变量添加在单选按钮的新属性
[UIHint("YesNoRadio")]
[Required(ErrorMessage = "test")]
public bool? Emergency { get; set; }
这将创建HTML作为
<div class="radio-inline"><label>
<input data-val="true" data-val-required="Test" id="Emergency" name="Emergency" type="radio" value="true">Yes</label>
</div>
<div class="radio-inline"><label>
<input id="Emergency" name="Emergency" type="radio" value="false">No</label>
</div>
我想要的是加新属性,可以说div-effect =“emergencyExplain”和单选按钮来作为
<label><input id="Emergency" name="Emergency" type="radio" value="false" div-effect = "emergencyExplain">No</label>
YesNoRadio.cshtml低于:
@model bool?
<div class="radio-inline">
<label>
@if (Model.HasValue && Model.Value)
{
@Html.RadioButtonFor(x => x, "true", new { @checked = "checked" });
}
else
{
@Html.RadioButtonFor(x => x, "true");
}
Yes
</label>
</div>
<div class="radio-inline">
<label>
@if (Model.HasValue && !Model.Value)
{
@Html.RadioButtonFor(x => x, "false", new { @checked = "checked" });
}
else
{
@Html.RadioButtonFor(x => x, "false");
}
No
</label>
</div>
以及其作为所谓:
@Html.EditorFor(m => m.Emergency, new { htmlAttributes = new { @class = "form-control" } })
新来的MVC形式创作所以在正确的方向指向任何帮助将不胜感激。
感谢
答
使用[UIHint]
属性只指示EditorFor()
方法来使用该模板。它不会将任何其他数据传递给模型属性以外的其他数据。您需要使用this overload的EditorFor()
,您需要传递模板的名称和代表additionalViewData
的对象。
您没有显示包含您要添加到data-effect
属性值的模型属性,但假设其
public string Effect { get; set; }
和您通过模型,然后设置其在GET方法值视图,然后删除自Emergency
财产[UIHint]
属性和修改主视图
@Html.EditorFor(m => m.Emergency, "YesNoRadio", new { effect = Model.Effect })
然后YesNoRadio.cshtml
模板更改为
<div class="radio-inline">
<label>
@Html.RadioButtonFor(x => x, true, new { id = "", div_effect = ViewData["effect"] })
<span>Yes</span>
</label>
<label>
@Html.RadioButtonFor(x => x, false, new { id = "", div_effect = ViewData["effect"] })
<span>No</span>
</label>
</div>
将产生
<input data-val="true" data-val-required="Test" div-effect="emergencyExplain" name="Emergency" type="radio" value="True">
有几件事情需要注意当前视图代码。
- 使用
new { htmlAttributes = new { @class = "form-control" } }
不会做任何事情,使用自定义EditorTemplate
时 - 其唯一 适用使用内置模板(如何将它知道哪些 元素以应用类)。如果您希望课程名称应用于单选按钮 ,请在的RadioButtonFor()
方法中添加该模板 - 您不需要(也不应该)设置
checked
属性。 即属性由基于属性(的 值RadiobuttonFor()
方法设置如果null
,没有按钮被选择, ,如果它的true
或false
然后相应的按钮将是 选择 - 还要注意使用的
new { id = "" }
其去除id
属性这将其他明智地产生重复这 无效的HTML
+0
感谢您的详细解释。正是我想要的,今天学到了新东西:)。 – Jay
是“emergencyExplain”模型中的一个属性的值?你需要证明你的'YesNoRadio.cshtm l'模板 –
是“emergencyExplain”是我模型中的另一个变量。不知道'''YesNoRadio.cshtml'''是一个模板,谢谢指针。 – Jay