RadioButtonFor,EditorFor,xxxFor on Property传入Partials

时间:2010-11-12 18:36:20

标签: asp.net-mvc asp.net-mvc-2

我的模型上的许多属性需要表示一组简单的是/否单选按钮。我需要检查相应的单选按钮以获取预先输入的值。我偏袒了。这是我做的:

RadioButtonsYesNo.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)); %>

是否有传递感兴趣的属性并正确渲染RadioButtonFor的最佳做法?

感谢。

2 个答案:

答案 0 :(得分:6)

或者在Razor中:

@{
    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")
}

答案 1 :(得分:1)

为什么不在编辑器模板中使用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) %>