c# - ASP.NET MVC 3 动态表单生成

标签 c# asp.net asp.net-mvc-3 reflection razor

我正在尝试在运行时生成一个表单。我最终采用了这种方法

@using (Html.BeginForm()) {
    @foreach (var propertyInfo in typeof(MvcApplication1.Models.LogOnModel).GetProperties()) {
        if (propertyInfo.PropertyType == typeof(Boolean)) {
            Html.CheckBoxFor(m => new PropertyWrapper<Boolean>(propertyInfo, Model).Property);
        }
        else if (propertyInfo.PropertyType == typeof(String)) {
            Html.TextBoxFor(m => new PropertyWrapper<String>(propertyInfo, Model).Property);
        }
        ...
    }
}

使用此类允许 [ElementType]For() 方法工作(它们需要对无法使用反射检索的属性的引用)。

public class PropertyWrapper<T> {
    private PropertyInfo _propertyInfo;
    private Object _instance;

    public PropertyWrapper(PropertyInfo propertyInfo, Object instance) {
        _propertyInfo = propertyInfo;
        _instance = instance;
    }

    public T Property {
        get { return (T)_propertyInfo.GetValue(_instance, null); }
        set { _propertyInfo.SetValue(_instance, value, null); }
    }
}

我收到以下错误

System.Reflection.TargetException: Non-static method requires a target.

因为 PropertyWrapper 构造函数的 instance 参数为 null。我错过了什么吗?这可能吗?

最佳答案

忘掉强类型、XXXFor 助手和 lambda 表达式吧。一旦开始反射游戏,您就必须玩到底。

XXXFor 帮助程序使用非常简单的表达式,例如属性访问。

m => new PropertyWrapper<String>(propertyInfo, Model).Property远远超出了那些 helper 的能力范围。

关于c# - ASP.NET MVC 3 动态表单生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9981724/

相关文章:

c# - 用这个。访问内部类成员?

c# - MVC 数据注释正则表达式不允许空格和逗号

asp.net - 是否可以使用 Javascript 禁用服务器端按钮的提交行为

javascript - 在 IE11 中出现 Javascript 严重错误

c# - MVC3 : How to check recaptcha with Ajax or directly with JS?

c# - linq to sql 选择作为命令

c# - 如何在 C# 中使用 GetNextWindow()?

c# - 提交点击并重定向时直接下载 pdf

c# - ModelMetaData、Custom Class Attributes 和一个难以描述的问题

asp.net - 如何将 razor 变量作为参数传递给 jquery 函数