Search code examples
c#genericsrazorasp.net-mvc-5system.reflection

Generic Editor Template


Is it possible to create a generic view with System.Reflection ?

So I could loop throught the class properties creating inputs with the @Html.EditorFor or @Html.Editor or even a normal <input />.

With this I could create a template and re-use it to save time and create a pleasant image to the users.

So is it possible?


Solution

  • Yes, it is possible, the model of the view should be object, and the controller can be an generic controller, but you should build your own ControllerControllerFactory like:

        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
                }
            }
        }