如何从视图中检索传递给我的自定义EditorFor的对象属性的VALUE?

时间:2022-08-22 15:14:23

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.

System.Web.Mvc有一个HtmlHelper,它包含一个名为EditorFor的方法,该方法呈现与视图中的数据类型相关联的编辑控件。

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

我试图通过扩展ASP.NET MVC 2 HtmlHelper来创建自己的EditorFor方法。我有以下内容:

    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?

任何人都可以解释我如何检索从视图传递给它的对象属性的VALUE?

1 个解决方案

#1


1  

You need to use a ModelMetadata:

您需要使用ModelMetadata:

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

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

然后,您可以从metadata.Model属性中获取值。

#1


1  

You need to use a ModelMetadata:

您需要使用ModelMetadata:

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

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

然后,您可以从metadata.Model属性中获取值。