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

前端 未结 2 1378
青春惊慌失措
青春惊慌失措 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())
    {
        <div class="form-group">
            @Html.Label(prop.Name)
            <div class="col-sm-9">
                @Html.Editor(prop.Name)
                @Html.ValidationMessage(prop.Name)
            </div>
        </div>
    }
    

    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/

    0 讨论(0)
  • 2021-01-02 18:05

    I believe that's not possible the way you want it. Try to use this instead :

    @Html.ValidationSummary()
    
    0 讨论(0)
提交回复
热议问题