0

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.

Simon
  • 7,991
  • 21
  • 83
  • 163

1 Answers1

0

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());
    }
  }
}
  • I have done as you have suggested, yet the DisplayWithIdFor cannot be found when using the @Html. syntax. – Simon Nov 18 '14 at 00:44
  • Have you included a reference to it in your view? `@using YourAssembly.Html;`? Or if your want to use it in other views as well, add it to `web.config`. –  Nov 18 '14 at 00:46
  • Note you can simplify this a bit by deleting the `var id = ...` line and replacing `html.MergeAttribute("id", id)` with `html.GenerateId(ExpressionHelper.GetExpressionText(expression));` –  Nov 18 '14 at 00:55