简体   繁体   中英

How to build a GENERIC ASP. NET MVC CRUD VIEW using object as model

I would like to create MVC generic CRUD views for any models... Lets have 2 models

public class MyObject1 {
    Display(Name = "Attribute 11", ShortName = "A11")]
    public String attribute11 { get; set; }
    Display(Name = "Attribute 12", ShortName = "A12")]
    public String attribute12 { get; set; }
}

public class MyObject2 {
    Display(Name = "Attribute 21", ShortName = "A21")]
    public String attribute21 { get; set; }
    Display(Name = "Attribute 22", ShortName = "A22")]
    public String attribute21 { get; set; }
}

I tried to build a Create view independant of the two models, a first try was to iterate through the public property of the Model (either MyObject1 or MyObject2) and try to rebuild a view from it.

@model Object
@{
    Type myType = Model.GetType();
    System.Reflection.PropertyInfo[] myProps = myType.GetProperties();
}
@using (Html.BeginForm()) {
    foreach (var f in myProps)
    {
        <div>
            @Html.LabelFor(o => f.Name)
            <div>
                @Html.EditorFor(o => f.Name)
                @Html.ValidationMessageFor(o => f.Name)
            </div>
        </div>
    }
    <div>
        <input type="submit" value="Create"/>
    </div>
}

Results

  • The labels are displaying the string "name" (!), and I would like to display the corresponding DisplayName meta-data
  • The Editor is displaying the property name (attribute11, attribute 12, ...) beacause of f.Name. I cannot display the values...
  • I have not checked the ValidationMessage yet

Any ideas how to manage this?

Thanks

Just use @Html.EditorFor(model=>model) your view should look:

@model Object
@using (Html.BeginForm()) {
    <div>
            @Html.EditorFor(model => model)
    </div>
    <div>
        <input type="submit" value="Create"/>
    </div>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM