我正在构建一个 ASP.NET MVC 2 网站,现在,我的 View 中有难看的意大利面条代码,我想将其制作成自定义 HtmlHelper。 View 中的当前代码是:
<%switch (Model.fiFieldTypeID) %>
<%
{
case 1: // Text area
Response.Write(Html.Encode(Html.TextAreaFor(model => model.fiStrValue)));
Response.Write(Html.Encode(Html.ValidationMessageFor(model => model.fiStrValue)));
break;
case 2: // Text box
Response.Write( Html.Encode(Html.TextBoxFor(model => model.fiStrValue)));
Response.Write( Html.Encode(Html.ValidationMessageFor(model => model.fiStrValue)));
break;
etc....
我试图将这段代码封装到一个简洁的小 HtmlHelper 中。我是这样开始的:
public class FormHelpers
{
public static MvcHtmlString GetStreamFieldEditor(this HtmlHelper html, FieldInstance field)
{
string output = "";
switch (field.fiFieldTypeID)
{
case 1: // Text area
output += html.TextAreaFor(field=> field.fiStrValue).ToString();
etc....
我知道我的 lamda 是错误的...但我更担心的是 TextAreaFor 不能用作方法。但是,普通的旧 TextArea 可用。我不想使用 TextArea 因为我需要保留我的模型绑定(bind)。如何在我的自定义 html 帮助程序中使用 TextAreaFor、TextBoxFor 等?
请您参考如下方法:
这个怎么样:
public static class FormHelpers
{
public static MvcHtmlString GetStreamFieldEditor(
this HtmlHelper<YourModelType> html)
{
var model = html.ViewData.Model;
if (model.fiFieldTypeID == 1)
{
return html.TextAreaFor(x => x.fiStrValue);
}
return html.TextBoxFor(x => x.fiStrValue);
}
}
然后:
<%: Html.GetStreamFieldEditor() %>
<%: Html.ValidationMessageFor(x => x.fiStrValue) %>
