I can't seem to figure out how to use scaffolding to create an Edit view for a model class that contains a collection of another class (the foreign key table). Please see below the simplifed model classes -
<code>
public class PrimaryKeyTable {
public int PrimaryKeyId {get;set}
public ICollection<ForeignKeyTable> ForeignKeyCollection {get;set;} //Each item in the collection maps to a row in the foreign key table in database
}
public class ForeignKeyTable {
public int PrimaryKeyId {get;set} //This links it back to PrimaryKey Class
public int ForeignKeyId {get;set}
public string Prop1 {get;set;}public string Prop2 {get;set;} //and so on
}
</code>
Now, this much is automatically created by the entity model. I want to create a strongly typed Edit view that takes PrimaryKeyTable as its Model and allows editing of the ForeignKeyCollection as well. I am able to loop over and create an editable table for ForeignKeyCollection, but it never posts back the edited values.
Below is simplified view -
<code>
@model DBModels.PrimaryKeyClass
@using (Html.BeginForm()) {
@Html.EditorFor(model => model.PrimaryKeyId)
<table>//The table will also have jquery to add/delete rows
@foreach (var foreignKey in Model.ForeignKeyCollection) {
//Removed table generation html stuff
<td>@Html.EditorFor(model => foreignKey.Prop1)</td>
//Also tried replacing the above with indexed names
}}
</code>
Simplified Controller -
<code>
public ActionResult Edit(PrimaryKeyTable primaryKeyTable) {
if (ModelState.IsValid) {
db.Entry(lookuptable).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(primaryKeyTable);
}
</code>
Now, below are my questions -
- Is it possible to use the automatic scaffolding feature to generate Create/Edit views that can automatically take collection properties of a model in account?
- Even though the Edit view will cater to only the editing for the PrimaryKeyTable, for the ForeignKeyCollection it'll be doing all of Create, Edit and Delete operations. How would the controller look like in that case?
- I'm considering creating a ViewModel that'll basically recreate the model classes. Then in the View, I could potentially write the HTML following the ASP.NET Wire Format approach by hanselman. It still requires a lot of work considering most of my model has such relationships (some go 2-4 levels deep). Is there a better approach to automate the code generation somehow (guess this goes back to how to use scaffolding)?
Aucun commentaire:
Enregistrer un commentaire