如何将不同模型类型的视图中的局部视图数据传递给控制器

时间:2017-07-14 04:24:33

标签: c# asp.net asp.net-mvc

我试图传递一个由' List'组成的ViewModel。实体和一系列的“书”。对象'创建'在我的控制器中发布方法。帖子将返回列表,但不会返回任何书籍。我不确定我是否正确设置了这个,或者我是否使用了错误的模型进行局部视图。

ListWithBooksViewModel:

public class ListWithBooksViewModel
{
    public BookList List { get; set; }
    public Book[] Books { get; set; }
}

'创建'视图:

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

&#39; AddBookPartial&#39;部分观点:

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

&#39;创建&#39; 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");
        }

2 个答案:

答案 0 :(得分:0)

抱歉,您不能拥有&#34; 嵌套表单&#34;或BeginForm中的BeginForm。

您正在使用另一个BeginForm将BeginForm嵌套在PartialView中。

您可以参考此链接作为附加参考:Html.BeginForm inside of Html.BeginForm MVC3

答案 1 :(得分:0)

请添加循环,然后添加 RenderPartial 传递您的对象。

@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>
    foreach (var book in Books)
    {
        Html.RenderPartial("AddBookPartial", book);
    }
    <p align="center">
        <input type="submit" value="Create List" />
    </p>
}