I am trying to write some HtmlHelper
extension to clean up my views. I have a need to use Html.DisplayFor()
to render my model. I write the following extension
public static MvcHtmlString MakeTableBodyTd(this HtmlHelper html, ModelMetadata metaData)
{
var td = new TagBuilder("td");
if (metaData != null)
{
var cssClassName = metaData.AdditionalValues.GetValueOrDefault("TextAlignment", "left");
td.AddCssClass(cssClassName);
var t = html.DisplayFor(x => metaData.Model, metaData.DataTypeName, new { Metadata = metaData }).ToHtmlString();
td.InnerHtml = t;
}
return new MvcHtmlString(td.ToString());
}
However, this extension is giving me this error
'HtmlHelper' does not contain a definition for 'DisplayFor' and no extension method 'DisplayFor(...)' accepting a first argument of type 'HtmlHelper' could be found (are you missing a using directive or an assembly reference?
I am able to use @Html.DisplayFor(...)
in my views with no issues, but unable to use the in the extensions class.
I have added a reference to the following libraries
using System.Web.Mvc;
using System.Web.Mvc.Html;
But still giving me the error.
The html has only the following methods available html.Display()
, html.DisplayForModel()
, html.DisplayName()
, html.DisplayNameForModel()
and html.DisplayText()
How can I use the html.DisplayFor(...)
method inside my extension?
You need to change the the signature of the method to include <TModel>
in order to use the ***For()
methods.
public static MvcHtmlString MakeTableBodyTd<TModel>(this HtmlHelper<TModel> html, ModelMetadata metaData)
{
....
}