【问题标题】:Generic Editor Template通用编辑器模板
【发布时间】:2016-10-11 19:40:13
【问题描述】:

是否可以使用 System.Reflection 创建通用视图?

所以我可以loop 通过class properties 创建inputs@Html.EditorFor@Html.Editor 甚至是普通的<input />

有了这个,我可以创建一个template 并重新使用它来节省时间并为用户创建一个令人愉快的图像。

那么有可能吗?

【问题讨论】:

    标签: c# generics razor asp.net-mvc-5 system.reflection


    【解决方案1】:

    是的,有可能,视图的模型应该是对象,控制器可以是通用控制器,但你应该构建自己的ControllerControllerFactory,如:

        public class MyGenericControllerFactory : DefaultControllerFactory
        {
            public override IController CreateController(RequestContext reqContext, string controllerName)
            {
                if(is controlleName generic) //you should define how build controller name when is generic
                //it should contain the controller name and the generic type name
                {
                    string contRealName = "";//get the real controller name from controllerName var
                    string genTypeName = ""; //get the generic type name fomr controllerName var
                    Type contType = Type.GetType(contRealName);
                    Type genType = Type.GetType(genTypeName);
                    contType = contType.MakeGenericType(genType);
                    return an instance of contType from your IoC container
                }
                else
                {
                    Type contType = Type.GetType(controllerName);
                    return an instance of contType from your IoC container
                }
            }
        }
    

    【讨论】:

    • 我使用了你的答案和其他东西,我创建了一个 .cshtml 文件或替换它,然后我循环遍历 properties ,如果该属性将我引导到 recursive loop 我忽略它,如果它是IEnumerable<T> 的实现,我会附加一个@Html.DropdownList(propName) 并将ViewBag 添加到ViewContext,并使用AI 自动生成linq 查询,这就像一个大的通用StringBuilder 来生成和读取@ 987654330@文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    相关资源
    最近更新 更多