Well, I read the Phil Haack article on list binding, and it works fine for me on a single view. But that I am stuck when I do this from the master record.
I have a very simple form for this object
public class Master
{
public int ID { get; set; }
public string MasterTitle { get; set; }
public virtual IList<Detail> Details { get; set; }
}
public class Detail
{
public int ID { get; set; }
public string DetailName { get; set; }
public virtual Master Master { get; set; }
}
A collection of forms is returned with the expected prefixes:
[0] ""
[1] "ID"
[2] "MasterTitle"
[3] "Details[0].ID"
[4] "Details[0]"
[5] "Details"
[6] "Details[0].DetailName"
[7] "Details[1].ID"
[8] "Details[1]"
[9] "Details[1].DetailName" string
And Controller.UpdateModel (master) correctly binds all properties. But when I call dbContext.SaveChanges, it returns the next sql from the sql profiler (psuedo code)
update detail1 set masterID = null
update detail2 set masterID = null
update master set masterName = 'newname'
insert detail1 ...
insert detail2 ...
I have a job that works, but it's pretty hacky, and I currently don't pick up the keys, so it depends on everything that comes back in the correct order. In addition, I need to include all the fields that I want to update.
public ActionResult Edit(FormCollection collection)
{
try
{
using (var ctx = new PlayContext())
{
var id = int.Parse(collection["ID"]);
Master master = ctx.Master.Find(id);
UpdateModel(master, new [] {"MasterTitle"});
for (int i = 0; i < master.details.Count; i++)
{
UpdateModel(master.details[i], "Details[" + i + "]", new[] { "DetailName" });
}
ctx.SaveChanges();
return View(master);
}
}
catch (Exception e)
{
ModelState.AddModelError("", e);
}
return View();
}
, UpdateModel - .
- , ? , , !