2

我正在尝试将一些常用代码重构为帮助程序扩展并且坚持使用语法,主要是因为我没有完全掌握泛型、lambda 表达式等。

我希望能够将它放在我的视图中,并让它使用我的模型的字段(例如 FirstName)来生成一些利用其他 Razor 扩展的 HTML:

@MyHelpers.BootstrapFormItem(m => m.FirstName)

目前我有:

@using System.Web.Mvc;
@using System.Web.Mvc.Html;
@using System.Linq;
@using System.Linq.Expressions;

@helper BootstrapFormitem(XXXXXXXXX) 
{
         <div class="control-group">
            @Html.LabelFor(XXXXXXX)
            <div class="controls">
               @Html.DisplayFor(XXXXX)
               @Html.ValidationMessageFor(XXXX)
            </div>
         </div>
}

问题:

  1. 这是正确的方法吗?我希望能够将此方法与任何视图模型字段一起使用。
  2. 我是否包含了正确的命名空间?这将进入 app_code 文件夹
  3. XXXXXX 里有什么?
4

1 回答 1

2

这个类做你需要的,我一直使用这些:

using System;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class HtmlHelpers
{
    public static MvcHtmlString BootstrapFormItem<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
    {
        StringBuilder html = new StringBuilder("<div class=\"control-group\">");
        html.AppendLine(helper.LabelFor(expression).ToString());
        html.AppendLine("<div class=\"controls\">");
        html.AppendLine(helper.DisplayFor(expression).ToString());
        html.AppendLine(helper.ValidationMessageFor(expression).ToString());
        html.AppendLine("</div>");
        html.AppendLine("</div>");
        return MvcHtmlString.Create(html.ToString());
    }
}

Note that this is a static class and also an extension method, the first input parameter is prefixed with 'this' which means it will extend (show up after you type a '.' in Intellisense) any objects of type HtmlHelper<TModel>. I will generally put this class in a Utilities folder. I often use a namespace as well and reference it from the web.config.

EDIT TO ANSWER QUESTIONS:

Here is the usage, it is covered by Intellisense as well:

@model MyClass

@Html.BootstrapFormItem(x => x.Name)

This is the output:

<div class="control-group">
    <label for="Name">Name</label>
    <div class="controls">
        naspinski
        <span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"/>
    </div>
</div>
于 2012-07-24T16:22:27.733 回答