Search code examples
asp.netasp.net-mvc-3models

populate view based on multi-level model


Suppose, I have models:

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

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

How represent view for Edit method based on Person model (MVC 3)?


Solution

  • You may try something along the lines of:

    @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>
    }
    

    and then you will define an editor template for the Book type (~/Views/Shared/EditorTemplates/Book.cshtml) which will be rendered for each element of the Book property collection (which by the way you would have named Books in order to follow standard conventions) on your view model:

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

    As far as your controller actions are concerned, it's pretty standard stuff:

    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");
    }