基于多级模型填充视图

时间:2012-01-03 14:40:17

标签: asp.net asp.net-mvc-3 models

假设我有模特:

public class Person
{
  public sting Name {get;set;}
  public List<Book> Books {get;set;}
}

public class Book
{
  public sting NameBook {get;set;}
}

如何基于Person模型(MVC 3)表示Edit方法的视图?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方式:

@model Person
@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.Name)
        @Html.EditorFor(x => x.Name)
    </div>
    @Html.EditorFor(x => x.Book)
    <button type="submit">Edit</button>
}

然后您将为Book类型(~/Views/Shared/EditorTemplates/Book.cshtml)定义一个编辑器模板,该模板将为Book属性集合的每个元素呈现(按照您的方式在视图模型上命名Books以遵循标准约定:

@model Book
<div>
    @Html.LabelFor(x => x.NameBook)
    @Html.EditorFor(x => x.NameBook)
</div>

就控制器操作而言,这是非常标准的东西:

public ActionResult Edit(int id)
{
    var person = _personRepository.Get(id);
    return View(model);
}

[HttpPost]
public ActionResult Edit(Person person)
{
    if (!ModelState.IsValid)
    {
        return View(person);
    } 
    _personRepository.Update(person);
    return RedirectToAction("Success");
}