2

我希望有人可以提供一个简单、直接的示例来扩展 Html.TextBoxFor 助手。我想包含一个布尔 ReadOnly 参数,它将(惊喜,惊喜,惊喜)呈现控件只读,如果为真。我已经看到了一些不太成功的示例,但是我尝试了以下方法,HtmlHelper 参数看到的 TextBoxFor 的唯一签名是我正在创建的签名(我是否缺少 using 语句?) :

public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, bool disabled)
    {
        var values = new RouteValueDictionary(htmlAttributes);

        if (disabled)
            values.Add("disabled", "true");

        return htmlHelper.TextBoxFor(expression, values)); //<-- error here
    }

我希望一个简单的例子能帮助我走上正轨。

谢谢。

4

2 回答 2

2

确保你using System.Web.Mvc.Html;在你的扩展类中调用HtmlHelper.TextBoxFor<>.

public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TProperty>> expression, 
    object htmlAttributes, 
    bool disabled)
    {
        var values = new RouteValueDictionary(htmlAttributes);
        // might want to just set this rather than Add() since "disabled" might be there already
        if (disabled) values["disabled"] = "true";
        return htmlHelper.TextBoxFor<TModel, TProperty>(expression, htmlAttributes);
    }
于 2010-09-01T13:08:18.317 回答
1

您在这一行上有一个左括号和两个右括号。应该:

return htmlHelper.TextBoxFor(expression, values);

还要使您的 HTML 更符合标准:

values["disabled"] = "disabled";
于 2010-09-01T14:27:38.173 回答