我的剃刀视图(MVC 5)中的代码正在使用以下模式重复,例如FirstName,LastName,ShortName等。我想知道是否可以封装到单个HTML Helper,它可以接受强类型lambda表达式和为我生成以下HTML?
@Html.TextBoxFor(m => m.FirstName, new { @class = "validate" })
@Html.LabelFor(m => m.FirstName)
<span class="red-text">
@Html.ValidationMessageFor(m => m.FirstName)
</span>
@Html.TextBoxFor(m => m.LastName, new { @class = "validate" })
@Html.LabelFor(m => m.LastName)
<span class="red-text">
@Html.ValidationMessageFor(m => m.LastName)
</span>
@Html.TextBoxFor(m => m.ShortName, new { @class = "validate" })
@Html.LabelFor(m => m.ShortName)
<span class="red-text">
@Html.ValidationMessageFor(m => m.ShortName)
</span>
理想情况下,我想写一下:
@Html.DisplayTextBox(m => m.FirstName)
@Html.DisplayTextBox(m => m.LastName)
@Html.DisplayTextBox(m => m.ShortName)
我认为,这有可能实现,但我不知道如何?我希望有人可以帮助我或指出我可以阅读并编写代码的资源吗?
我不想依赖EditorTemplate,因为我想控制表单格式。
答案 0 :(得分:1)
您可以创建自己的HtmlHelper扩展方法来生成组合输出。以下将创建html your after
using System;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace YourAssembly.Html
{
public static class MyHelpers
{
public static MvcHtmlString DisplayTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
MvcHtmlString label = LabelExtensions.LabelFor(helper, expression);
MvcHtmlString textbox = InputExtensions.TextBoxFor(helper, expression, new { @class = "validate" });
MvcHtmlString validation = ValidationExtensions.ValidationMessageFor(helper, expression);
StringBuilder html = new StringBuilder();
html.Append(textbox);
html.Append(label);
TagBuilder span = new TagBuilder("span");
span.AddCssClass("red-text");
span.InnerHtml = validation.ToString();
html.Append(span.ToString());
return MvcHtmlString.Create(html.ToString());
}
}
}
然后,您可以通过将其添加到web.config
使其在所有视图中可用<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
....
<add namespace="YourAssembly.Html" />
</namespaces>