我希望有人可以提供一个简单,直接的例子来扩展Html.TextBoxFor帮助器。我想包含一个布尔的ReadOnly参数,它将(惊讶,惊讶,惊讶)渲染控件只读为true。我已经看到了一些没有完全解决问题的例子,但是我尝试了以下内容,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
}
我希望一个简单的例子可以帮助我走上正轨。
感谢。
答案 0 :(得分: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);
}
答案 1 :(得分:1)
此行上有一个开头和两个右括号。应该是:
return htmlHelper.TextBoxFor(expression, values);
还要使您的HTML更加标准化:
values["disabled"] = "disabled";