I'm trying to pass a ViewModel consisting of the 'List' entity and an array of 'Book' objects to the 'Create' Post method in my controller. The post will return the list but not any books. I'm not sure if I'm setting this up correctly or if I'm using the wrong model for the partial view.
ListWithBooksViewModel:
public class ListWithBooksViewModel
{
public BookList List { get; set; }
public Book[] Books { get; set; }
}
'Create' View:
@model LitList.Models.ListWithBooksViewModel
@using (Html.BeginForm("Create", "List", FormMethod.Post))
{
<div>List Name: @Html.EditorFor(l => l.List.ListName)</div>
<div>Subject of List: @Html.EditorFor(l => l.List.Subject)</div>
Html.RenderPartial("AddBookPartial");
Html.RenderPartial("AddBookPartial");
Html.RenderPartial("AddBookPartial");
<p align="center">
<input type="submit" value="Create List" />
</p>
}
'AddBookPartial' Partial View:
@model LitList.Domain.Entities.Book
@Html.BeginForm()
@Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
@Html.LabelFor(model => model.BookName)
<div class="col-md-10">
@Html.EditorFor(model => model.BookName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Author)
<div class="col-md-10">
@Html.EditorFor(model => model.Author)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.PublicationYear)
<div class="col-md-10">
@Html.EditorFor(model => model.PublicationYear)
</div>
</div>
</div>
'Create' ActionMethod:
[HttpPost]
public ActionResult Create(ListWithBooksViewModel newList)
{
BookList list = newList.List;
if (ModelState.IsValid)
{
foreach (var b in newList.Books)
{
b.ListRefId = list.ListId;
}
list.Books = newList.Books;
listRepo.SaveList(list);
TempData["message"] = string.Format("{0} has been saved", list.ListName);
return View("Index");
}
else
{
return View("Fail");
}