这个类做你需要的,我一直使用这些:
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>