代码之家  ›  专栏  ›  技术社区  ›  hoffmanc

属性上的RadioButtonFor、EditorFor、xxxFor传递到部分

  •  0
  • hoffmanc  · 技术社区  · 15 年前

    我的模型上的许多属性需要用一组简单的“是/否”单选按钮表示。我需要检查相应的单选按钮是否有预先输入的值。我带着一部分去了。以下是我所做的:

    收音机按钮是不是ascx

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<KeyValuePair<string,string>>" %>
    <div id="<%:Model.Key %>">
    <%: Html.ValidationMessage(Model.Key)%>
    <ul class='RadioButtonsYesNo'><li>
    <%: Html.RadioButton(Model.Key, "Yes", Model.Value == "Yes", new { id = Model.Key + "_Yes" })%>
    <label for='<%: Model.Key %>_Yes'>Yes</label>
    </li><li>
    <%: Html.RadioButton(Model.Key, "No", Model.Value == "No", new { id = Model.Key + "_No" })%>
    <label for='<%: Model.Key %>_No'>No</label>
    </li></ul>
    </div>
    

    用法

    <% Html.RenderPartial("RadioButtonsYesNo", new KeyValuePair<string, string> ("MyProp",Model.MyProp)); %>
    

    是否有传递感兴趣的属性并使RadioButton正确呈现的最佳实践?

    谢谢。

    2 回复  |  直到 15 年前
        1
  •  6
  •   Jenn    15 年前

    或者剃刀:

    @{
        var yesRadioName = Model.Key + "_Yes";
        var noRadioName = Model.Key + "_No";
    
        @Html.RadioButtonFor(m => m.Key, true, new { @id = yesRadioName })
        @Html.Label(yesRadioName , "Yes")
        @Html.RadioButtonFor(m => m.Key, false, new { @id = noRadioName })
        @Html.Label(noRadioName, "No")
    }
    
        2
  •  1
  •   Darin Dimitrov    15 年前

    为什么不使用 RadioButtonFor 在编辑器模板中:

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
    <% string name = ViewData.TemplateInfo.GetFullHtmlFieldId(""); %>
    <div id="<%: name %>">
        <%: Html.ValidationMessageFor(x => x) %>
        <ul class="RadioButtonsYesNo">
            <li>
                <%: Html.RadioButtonFor(x => x, "Yes", new { id = name + "_Yes" }) %>
                <label for="<%: name %>_Yes">Yes</label>
            </li>
            <li>
                <%: Html.RadioButtonFor(x => x, "No", new { id = name + "_No" }) %>
                <label for="<%: name %>_No">No</label>
            </li>
        </ul>
    </div>
    

    然后:

    <%: Html.EditorFor(x => x.MyProp) %>