Search code examples
asp.net-mvc-5html-helperasp.net-mvc-viewsdisplayfor

Using a HtmlHelper in MVC 5


I am coding an MVC 5 internet application, and I wish to display the Id of a div when using the DisplayFor method in a view.

Here is some code that I have:

public static MvcHtmlString DisplayWithIdFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string wrapperTag = "div")
{
    var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
    return MvcHtmlString.Create(string.Format("<{0} id=\"{1}\">{2}</{0}>", wrapperTag, id, helper.DisplayFor(expression)));
}

This is the error that I am getting:

'System.Web.Mvc.HtmlHelper' does not contain a definition for 'DisplayFor' and no extension method 'DisplayFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)

I am not sure if I have placed the DisplayWithIdFor method in the correct place. I am wishing to use the DisplayWithIdFor method in the Edit view of a controller called AssetController, and have placed the DisplayWithIdFor method in the AssetController.

Can I please have some help with this code?

Thanks in advance.


Solution

  • Your method should be something like

    using System;
    using System.Linq.Expressions;
    using System.Web.Mvc;
    using System.Web.Mvc.Html;
    
    namespace YourAssembly.Html
    {
      public static class DisplayHelper
      {
        public static MvcHtmlString DisplayWithIdFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string wrapperTag = "div")
        {
          var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
          MvcHtmlString text = DisplayExtensions.DisplayFor(helper, expression);
          Tagbuilder html = new TagBuilder(wrapperTag);
          html.MergeAttribute("id", id);
          html.InnerText = text;
          return MvcHtmlString.Create(html.ToString());
        }
      }
    }