通过 MVC 模型变量在 RadioButton 上添加新属性

Adding new attributes on RadioButton through MVC model variable

我有 MVC class 并且其中一个变量已声明为:

[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() 方法使用该模板。除了模型 属性 之外,它不会将任何其他数据传递给模板。您需要使用 EditorFor()this overload 来传递模板名称和代表 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">

关于当前视图代码的一些注意事项。

  1. 使用new { htmlAttributes = new { @class = "form-control" } } 使用自定义 EditorTemplate 时不会做任何事情 - 它唯一的 适用于使用内置模板(它怎么知道哪个 class 应用到的元素)。如果您想要应用 class 名称 到单选按钮,将其添加到 RadioButtonFor() 方法中 模板
  2. 您不需要(也不应该)设置 checked 属性。 该属性由 RadiobuttonFor() 方法基于 属性 的值(如果是 null,则不会选择任何按钮, 如果它的 truefalse 那么相应的按钮将是 已选择
  3. 另请注意 new { id = "" } 的使用,它删除了 id 否则会生成重复项的属性 无效 html