How to get the VALUE value of an object property that is passed to the user editor ForFor from the view?

System.Web.Mvc has an HtmlHelper containing the EditorFor method, which displays the edit control associated with the data type in the view.

I am trying to create my own EditorFor method by extending ASP.NET MVC 2 HtmlHelper. I have the following:

public static string EditorForNew<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> item) { string value = ""; string name = item.ToString(); // THIS IS CORRECTED IN MY COMMENT TO THE ANSWER BELOW! Type type = typeof(TProperty); if (type == typeof(int) || type == typeof(int?) || type == typeof(double) || type == typeof(double?) || type == typeof(decimal) || type == typeof(decimal?) || type == typeof(float) || type == typeof(float?)) { return helper.TextBox(name, value, new { @class = "number" }).ToString(); } else { return helper.TextBox(name, value).ToString(); } } 

Can someone explain how I get the VALUE value of the property of the object that is passed to this from the view?

+4
source share
1 answer

You need to use ModelMetadata:

 ModelMetadata metadata = ModelMetadata.FromLambdaExpression(item, helper.ViewData); 

Then you can get the value from the metadata.Model property.

+1
source

All Articles