Reputation: 619
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
Any ideas how to manage this?
Thanks
Upvotes: 0
Views: 1001
Reputation: 1879
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>
}
Upvotes: 0