Pete
Pete

Reputation: 58432

Pass model tproperty expression to partial

I have a lot of yes / no radio buttons on a form like this:

<div class="form-row">                                   
    @Html.DisplayNameFor(m => m.OptIn48Hours)<br />

    <label>@Html.RadioButtonFor(m => m.OptIn48Hours, "true") Yes</label>
    <label>@Html.RadioButtonFor(m => m.OptIn48Hours, "false") No</label>
    @Html.ValidationMessageFor(m => m.OptIn48Hours)
</div>

So I thought I would make this into a partial

@model object
<div class="form-row">                                   
    @Html.DisplayNameFor(Model)<br />

    <label>@Html.RadioButtonFor(Model, "true") Yes</label>
    <label>@Html.RadioButtonFor(Model, "false") No</label>
    @Html.ValidationMessageFor(Model)
</div>

I don't know how to pass the m.OptIn48Hours part to the partial. I thought I could just use

@Html.Partial("_RadioYesNo", Model.OptIn48Hours)

But this just passes the value through to the partial instead of whatever m.OptIn48Hours is. How do I pass in m.OptIn48Hours

Upvotes: 1

Views: 343

Answers (1)

user3559349
user3559349

Reputation:

I would recommend a html helper extension method to generate the controls

public static MvcHtmlString YesNoButtonsFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, bool>> expression)
{
    ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
    string name = ExpressionHelper.GetExpressionText(expression);
    // ensure we use unique `id` attributes if being used in a collection
    string id = HtmlHelper.GenerateIdFromName(name) ?? metaData.PropertyName;
    StringBuilder html = new StringBuilder();
    TagBuilder label = new TagBuilder("div");
    label.InnerHtml = helper.DisplayNameFor(expression).ToString();
    html.Append(label);
    string yesId = string.Format("{0}_Yes", id);
    html.Append(helper.RadioButtonFor(expression, true, new { id = yesId }));
    html.Append(helper.Label(yesId, "Yes"));
    string noId = string.Format("{0}_No", metaData.PropertyName);
    html.Append(helper.RadioButtonFor(expression, false, new { id = noId }));
    html.Append(helper.Label(noId, "No"));
    html.Append(helper.ValidationMessageFor(expression));
    TagBuilder div = new TagBuilder("div");
    div.AddCssClass("form-row");
    div.InnerHtml = html.ToString();
    return new MvcHtmlString(div.ToString());
}

and use it in the view as

@Html.YesNoButtonsFor(m => m.yourBooleanProperty)

Upvotes: 3

Related Questions