本文介绍了将模型属性表达传递给局部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这样的表单上,我有很多是/不是单选按钮:

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>

我不知道如何将 m.OptIn48Hours 部分传递给该部分.我以为我可以使用

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)

但这只是将值传递给了局部变量,而不是m.OptIn48Hours .如何传递 m.OptIn48Hours

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

推荐答案

我建议使用html helper扩展方法来生成控件

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());
}

并在视图中将其用作

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

这篇关于将模型属性表达传递给局部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 21:08