开发者

edit parent and children in same view

How would I edi开发者_如何学编程t a parent and collection of child objects in the same view? Any good tutorials on how to do this with mvc3 and automatic binding?

Much appreciated!


The key would be to use the following syntax in your view for your child collection items:

data.Children.Index and data.Children[index].Properties

Here is a simple example:

Model:

public class Parent
{
  public int FieldA { get; set; }
  public string FieldB { get; set; }
}

public class Child
{
  public int Id { get; set; }
  public string Name { get; set; }
}

public class ParentChildViewModel
{
  public Parent Master { get; set; }
  public List<Child> Children { get; set; }
}

Controller:

public ActionResult Edit()
{
  return View(new ParentChildViewModel());
}

[HttpPost]
public ActionResult Edit(ParentChildViewModel data)
{
  // Save your objects
}

View:

@model ParentChildViewModel
...
@using(Html.BeginForm())
{
  @Html.TextBoxFor(x => x.Master.FieldA);

  @{ int index = 0; }
  @foreach(var c in Model.Children)
  {
    @Html.Hidden("data.Children.Index", index);
    @Html.TextBox("data.Children[" + index + "].Name")
    @{ index++; }
  }
}

On your controller you will receive on the .Children properties the changes made to the Name properties and on the .Master the changes made to the parent. The only trick is the data.Children syntax where data is the name of the variable name on you Controller. The data.Children.Index is required for each child and of course you have to increment the index.

Hope that help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜