您可以将Selected 布尔属性添加到您的作者,以了解他是否被选入给定书籍:
public class Author
{
public int IdAuthor { get; set; }
public bool Selected { get; set; }
public string Name { get; set; }
}
然后:
public class HomeController : Controller
{
public ActionResult Index()
{
var book = new Book
{
IdBook = 1,
Title = "foo bar",
Authors = new[]
{
new Author { IdAuthor = 1, Name = "author 1" },
new Author { IdAuthor = 2, Name = "author 2" },
new Author { IdAuthor = 3, Name = "author 3" },
}.ToList()
};
return View(book);
}
[HttpPost]
public ActionResult Index(Book book)
{
return View(book);
}
}
在视图中:
@model Book
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.Title)
@Html.EditorFor(x => x.Title)
</div>
for (int i = 0; i < Model.Authors.Count; i++)
{
@Html.CheckBoxFor(x => x.Authors[i].Selected)
@Html.LabelFor(x => x.Authors[i].Selected, Model.Authors[i].Name)
@Html.HiddenFor(x => x.Authors[i].Name)
}
<p>
<button type="submit">OK</button>
</p>
}