ASP.NET MVC 3 Razor DisplayFor Delegate

I get this error:

Templates can only be used with access to a field, access to properties, an index of a one-dimensional array, or one-parameter expressions of a custom indexer.

Here is my code (custom HTML helper, DisplayFor packaging, so I can select a template):

public static string DisplayLocationTypeFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, LocationType>> expression, bool plural = false)
{
   return plural ? 
      htmlHelper.DisplayFor(expression, "LocationTypePlural").ToHtmlString() :
      htmlHelper.DisplayFor(expression).ToHtmlString();
}

When I use it like this, it works:

@Html.DisplayLocationTypeFor(model => model.LocationType)

Because it modelhas a property for LocationType.

But when I do this in another special HTML helper:

public static MvcHtmlString SearchPreferenceButtonForModel<TModel>(this HtmlHelper<TModel> htmlHelper)
{
   // .. other code
   foreach (var property in htmlHelper.ViewData.ModelMetadata.Properties)
   {
      if (property.PropertyName == "LocationType")
         htmlHelper.DisplayLocationTypeFor(model => ((LocationType)Enum.ToObject(typeof(LocationType), property.Model)), true);
   } 
}

These are errors.

I can change the helper DisplayLocationTypeForto use htmlHelper.Displayinstead, but I'm not sure how to do it.

Any ideas?

, , , LocationType, . , URL-. , , .

, / LocationType.

+2
2

:

, , .

, Razor ( !) -. - , , . - :

if (property.PropertyName == "LocationType") {
  LocationType locationType = (LocationType) Enum.ToObject(typeof(LocationType), property.Model));
  htmlHelper.DisplayLocationTypeFor(model => locationType, true);
} 
+1

, LocationType.

- , , . :

  • ~/Views/Shared/DisplayTemplates.
  • LocationType , LocationType. , @DisplayFor(model => model.LocationType), , LocationType.
0

Source: https://habr.com/ru/post/1676699/


All Articles