Loop through Model properties in reflection, then use Html helpers to display. How to get concrete property back?

前端 未结 2 1377
青春惊慌失措
青春惊慌失措 2021-01-02 17:53

We have an MVC4 ASP.Net site that we are trying to use reflection to loop through properties of a model, and display the names/values/and other information using Html helper

2条回答
  •  走了就别回头了
    2021-01-02 18:05

    You don't need to use generic implementations for that (EditorFor, DisplayFor...), just use the non generic ones, Editor, Display...

    This will work just fine, you will get validation, automatic bindings and everything else, the whole nine yards...

    @foreach (PropertyInfo prop in Model.GetType().GetProperties())
    {
        
    @Html.Label(prop.Name)
    @Html.Editor(prop.Name) @Html.ValidationMessage(prop.Name)
    }

    If you want to experiment with generic implementations here is a great blog post on how to do that

    http://www.joelscode.com/use-mvc-templates-with-dynamic-generated-types-with-custom-htmlhelper-extensions/

提交回复
热议问题