如何将 list<object> 绑定到模型并与其他表单数据一起提交?

How to bind list<object> to a model and submit along with other form data?

这就是我想要做的:

我有一个带有一些输入字段的表单。部分表格允许用户选择多个选项(书籍),但不知道有多少。

型号:

public class Data
{
    public string name { get; set; }
    public string age { get; set; }
    ...
    public List<Books> books { get; set; }
    ...
}

并且,

public class Books
{
    public string Title { get; set; }
    public string Author { get; set; }
}

查看:

@model Applicants.Models.Data
...
<input type="text" name="Title" value="" />
<input type="text" name="Author" value="" />

我的问题是,如何提交多个标题和作者以及其他表单数据?以及如何正确命名输入字段?

我读过这个https://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

但是例子只提交了一个List,没有提交其他数据

谢谢。

你可以像这样为普通 html 语法的绑定模型做这只是一个例子 你需要根据你的需要修改

<input type="text" name="Model.name" value="Curious George" />
<input type="text" name="Model.age" value="H.A. Rey" />

<input type="text" name="Model.books[0].Title" value="Curious George" />
<input type="text" name="Model.books[0].Author" value="H.A. Rey" />    

由于您使用的是 Razor 视图,因此您可以使用强类型 @Html.TextBoxFor() 帮助程序并使用 for 循环在 books 列表中生成多个文本框:

@model Applicants.Models.Data

@using (Html.BeginForm())
{
    @Html.TextBoxFor(model => model.name)
    @Html.TextBoxFor(model => model.age)

    @for (int i = 0; i < Model.books.Count; i++)
    {
        @Html.TextBoxFor(model => model.books[i].Title)
        @Html.TextBoxFor(model => model.books[i].Author)
    }

    @* don't forget to add submit button here *@
}

循环将产生 <input> 元素,如下例所示,假设您有 POST 操作,其中 Applicants.Models.Data 作为视图模型参数:

<input name="books[0].Title" type="text" value="sometitle">
<input name="books[0].Author" type="text" value="somevalue">

<input name="books[1].Title" type="text" value="sometitle">
<input name="books[1].Author" type="text" value="somevalue">

<!-- other input elements depending on books list count -->

参考 this fiddle 工作示例。