ASP.NET MVC inline helper for fields

asp.net-mvc c# expression-trees html-helper razor

Question

To display fields, I need a general inline aid.

What I now have is as follows:

@helper DisplayField(Func<MyModel, string> field)
{
    if (string.IsNullOrWhiteSpace(field(Model)) == false)
    {
        <div class="row"> @field(Model) </div>     
    }
}

Usage:

@DisplayField(m => m.Name)
@DisplayField(m => m.PhoneNumber)

How to display Label(DisplayAttribute) inside of a helper is beyond my comprehension. Thank you.

1
4
12/22/2015 2:35:08 PM

Accepted Answer

ZZZ_tmp
7
11/28/2013 10:29:00 AM

Popular Answer

I'll leave my response here as @David 001 already gave a really beautiful MVC-solution for this; it illustrates the inner mechanism and may be useful if you need to handle an issue that isn't addressed by the MVC out of the box aids.

The argument type should be changed toFunc<MyModel, string> to Expression<Func<MyModel, string>> . Instead of the static delegate you would have received in the method's present form, you would instead obtain a dynamic expression that you could examine.
The field's value may be obtained in the following manner:

var compExpr = field.Compile();
var value = compExpr.DynamicInvoke(Model);

The dynamic expression's returned member and its characteristics may be accessed as follows:

var memberAccExpr = (System.Linq.Expressions.MemberAccessExpression)field.Body;
var attr = (DisplayAttribute)memberAccExpr.Member.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault();

I can't tell for sure if it works in Razor since I only tried it approximately in a C# project (not an MVC project), but I'm sure you could migrate your function to a standard class as well.
Please be aware that this method loses some type safety since a caller may provide the method with a variety of dynamic expressions. Therefore, if you evaluate the phrase to identify the property, you should consider this.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow