I’m creating my first MVC helper method, but can’t quite get it. I want to emit the same code as the standard “@Html.TextBoxFor” but with the attribute “title” and its value taken from the model property. This is what I have so far. You can see I’m trying to just use the standard “TextBoxFor” at the end and add my own attribute to it, but that doesn’t seem to be the way to do it.
public static MvcHtmlString TextBoxForWithTitle<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
return htmlHelper.TextBoxFor(expression, new { @title = metaData.DisplayName });
}
Specifically, I get a compile time error:
'System.Web.Mvc.HtmlHelper<TModel>' does not contain a definition for 'TextBoxFor' and no extension method 'TextBoxFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper<TModel>' could be found (are you missing a using directive or an assembly reference?) D:\DevData\JWilliams\Code\Sandbox\URIntakeMVC2\URIntake\HtmlHelpers.cs 16 31 URIntake
The TextBoxFor is an extension method for the
HtmlHelper<TModel>class which lives in theSystem.Web.Mvc.Htmlnamespace.And if you want to use an extension method you need to explicitly import its namespace with the
usingdirective. So you are missing theusing:And don’t forget that you are also creating an extension method here (
TextBoxForWithTitle), so when you want to use it in your view you also need tousingyour ownTextBoxForWithTitlemethods namespace: