开发者

RadioButtonFor, EditorFor, xxxFor on Property passed into Partials

Many of the properties on my model need to be represented a simple group of Yes/No radio buttons. I need to check the corresponding radio button for pre-entered values. I went with a partial. Here's what I did:

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>

Usage

<% Html.RenderPartia开发者_开发百科l("RadioButtonsYesNo", new KeyValuePair<string, string> ("MyProp",Model.MyProp)); %>

Is there a best practice for passing in the property of interest and having RadioButtonFor render correctly?

Thanks.


Or in 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")
}


Why not using RadioButtonFor in an editor template:

<%@ 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>

And then:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜