Marc
Marc

Reputation: 6771

C# ASP.net EditorTemplate - get name of the used model property

I have a razor view where I call this:

@Html.EditorFor(m => m.Code)

Then I have an EditorTemplate view which is rendered then, it looks like this:

@model string
@Html.HiddenFor(m=>m)

And I get this output:

<input id="Code" name="Code" type="hidden" value="" />

Everything fine.

But now I just want to get the property name Code inside the EditorTemplate view, not the whole input string. The @Html.HiddenFor(m=>m) method is able to get it from the model object somehow and put it into the input field but how can I do this?

(And no, I don't want to parse it from the input field string... :)

Upvotes: 0

Views: 142

Answers (1)

Ron Sijm
Ron Sijm

Reputation: 8738

@Html.HiddenFor(m=>m) seems kind of weird... but anyway:

HiddenFor uses Expression<Func<TModel, TProperty>> so you could make your own function to only return the name:

 public static class GenericHelper<T>
 {
     public static String GetPropertyName<TValue>(Expression<Func<T, TValue>> propertyId)
     {
         var operant = (MemberExpression)((UnaryExpression)propertyId.Body).Operand;
         return operant.Member.Name;
     }
}

And create a helper to use that inside your view, which is explained here

Upvotes: 1

Related Questions