代码之家  ›  专栏  ›  技术社区  ›  quakkels

如何在自定义htmlhelper中使用html.textrareafor()方法?

  •  1
  • quakkels  · 技术社区  · 15 年前

    我正在构建一个ASP.NET MVC 2网站,现在,我的视图中有一个丑陋的意大利面代码,我想把它制作成一个自定义的HTMLHelper。视图中的当前代码是:

                <%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....
    

    我知道我的拉姆达错了…但我更担心的是 TextAreaFor 不能作为方法使用。然而,普通老 TextArea 是可用的。我不想用 文本域 因为我需要保留我的模型绑定。我如何使用 特克斯塔罗 , TextBoxFor 等等,在我的自定义HTML助手中?

    2 回复  |  直到 15 年前
        1
  •  4
  •   Darin Dimitrov    15 年前

    这个怎么样?

    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) %>
    
        2
  •  0
  •   SLaks    15 年前

    添加 using System.Web.Mvc.Html .
    编辑 :确保您引用的是System.Web.MVC.dll v2.0或更高版本。

    要修复lambda,需要使用 System.Linq.Expressions .