1

我想重构视图表单代码以避免复制粘贴。但它不起作用。剃刀不允许写

@model System.Linq.Expressions.Expression<Func<TModel, TValue>> expression

@Html.Partial("Item", model => model.EmpName)

旧代码,有效:

        <tr>
            <td class="editor-label" style="border: 0;">
                @Html.LabelFor(model=>model.EmpName)
            </td>
            <td class="editor-field" style="border: 0">
                @Html.EditorFor(model=>model.EmpName)
                @Html.ValidationMessageFor(model=>model.EmpName)
            </td>
        </tr>
        <tr>
            <td class="editor-label" style="border: 0;">
                @Html.LabelFor(model=>model.Email)
            </td>
            <td class="editor-field" style="border: 0;">
                @Html.EditorFor(model=>model.Email)
                @Html.ValidationMessageFor(model=>model.Email)
            </td>
        </tr>

重构后不起作用:

项目.cshtml:

   @model System.Linq.Expressions.Expression<Func<TModel, TValue>> expression
        <tr>
            <td class="editor-label" style="border: 0;">
                @Html.LabelFor(expression)
            </td>
            <td class="editor-field" style="border: 0">
                @Html.EditorFor(expression)
                @Html.ValidationMessageFor(expression)
            </td>
        </tr>
    }

新代码:

 @Html.Partial("Item", model => model.EmpName)
 @Html.Partial("Item", model => model.Email)

如何让它发挥作用?

4

2 回答 2

2

您可以编写自己的 HtmlHelper 扩展方法,例如:

public static MvcHtmlString MyEditFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
    var group = new TagBuilder("div");
    group.InnerHtml = html.LabelFor(expression).ToString();
    //more formatting and controls here
    return MvcHtmlString.Create(group.ToString());
}

这将允许您编写:

@Html.MyEditFor(m => m.Name)

这种方法的缺点是您将无法内联 HTML,因为这不是视图。但是,它确实允许您设置标准控件布局。

于 2013-02-04T05:57:26.223 回答
2

找到了解决方案。感谢@Paul。

项目.cshtml:

 @model MyClientCustomValidation.Models.LabelEditorValidation 
        <tr>
            <td class="editor-label" style="border: 0;">
                @Model.Label
            </td>
            <td class="editor-field" style="border: 0">
                @Model.Editor
                @Model.Validation
            </td>
        </tr>

其中有型号:

public class LabelEditorValidation
{
    public MvcHtmlString Label { get; set; }
    public MvcHtmlString Editor { get; set; }
    public MvcHtmlString Validation { get; set; }     
}

和内部形式:

@Html.MyEditFor(model=>model.EmpName)
@Html.MyEditFor(model=>model.Email)

MyEditorFor 在哪里

public static MvcHtmlString MyEditFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
    {
        return html.Partial("Item", new LabelEditorValidation() { Label = html.LabelFor(expression), Editor = html.EditorFor(expression), Validation = html.ValidationMessageFor(expression) });
    }
于 2013-02-04T10:18:45.357 回答