类别中包含一个产品的集合属性,如何向数据库添加一条类别记录的同时,添加任意多个产品。
class="alt"> public class Product
{
[DisplayName("产品名称")]
public string Name { get; set; }
}
public class Category
{
[DisplayName("类别名称")]
public string Name { get; set; }
private IList<Product> _products = new List<Product>();
public IList<Product> Products
{
get { return _products; }
set { _products = value; }
}
}
控制器方法能接收的格式为:
Category.Name
Category.Products[0].Name
Category.Products[1].Name
...
前台视图使用jquery动态生成input,并把input的name属性设置成Category.Products[i].Name格式。
□ Home/Index.cshtml视图
@model AddingMultipleNestedData.Models.Category
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new {id = "addForm"}))
{
<div>
@Html.LabelFor(m => m.Name)
@*@Html.EditorFor(m => m.Name)*@
@Html.TextBox("Category.Name")
</div>
<div id="products"></div>
<div>
<input id="btnAddProduct" type="button" value="添加产品"/>
</div>
<div>
<input type="submit" value="提交"/>
</div>
}
@section scripts
{
<script type="text/javascript">
$(function() {
var noOfProducts = 0;
$('#btnAddProduct').click(function() {
var product = getNestedName("Category.Products", noOfProducts);
noOfProducts++;
$('#products').append("<input type='text' name='"+product+".Name' /><p>");
});
});
function getNestedName(itemName, itemNumber) {
return (itemName + "[" + itemNumber + "]");
}
</script>
}
没有添加产品前:
添加产品集合:
□ HomeController
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Create(Category category)
{
return View();
}
断点调试: