How do I retrieve the VALUE of the object's property that is passed to my custom EditorFor from the view?

StackOverflow https://stackoverflow.com/questions/11229391

Question

System.Web.Mvc has an HtmlHelper that contains a method called EditorFor that renders the editing control associated with a data type in a view.

Im trying to create my own EditorFor method by extending the 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 anyone explain how I retrieve the VALUE of the object's property that is passed to this from the view?

Était-ce utile?

La solution

You need to use a ModelMetadata:

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

You can then get the value from the metadata.Model property.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top