【发布时间】:2015-10-04 07:00:38
【问题描述】:
我正在开发 ASP.NET MVC Web 应用程序,我需要使用 checkboxs 将 List<ProdColor> 提交给 Controller。这是我的代码
型号
public partial class ProdColor
{
public int ProdColor_ID { get; set; }
public Nullable<int> P_ID { get; set; }
public Nullable<int> Color_ID { get; set; }
public virtual ProdctModelView ProdctModelView { get; set; }
}
public class ProdctModelView
{
public ProdctModelView()
{
this.ProductColors = new HashSet<ProdColor>();
}
public int P_ID { get; set; }
public string P_name { get; set; }
public virtual ICollection<ProdColor> ProductColors { get; set; }
}
控制器
public ActionResult Create()
{
ViewBag.colorlist = db.Colors.OrderBy(m => m.Color_name).ToList();
return View();
}
[HttpPost]
public ActionResult Create(ProdctModelView product, List<ProdColor> ProductColors)
{
Product prod = new Product();
//Save new product
db.Products.Add(prod);
db.SaveChanges();
foreach (var color in ProductColors)
{
color.P_ID = prod.P_ID;
db.ProdColors.Add(color);
}
db.SaveChanges();
return RedirectToAction("Index");
}
查看
@model mvc4test.Models.ProdctModelView
@using (Html.BeginForm("Create", "CP_Product", FormMethod.Post))
{
@for (int i = 0; i < ViewBag.colorlist.Count; i++)
{
<input type="checkbox" id="@ViewBag.colorlist[i].Color_name" name="[@i].Color_ID" value="@ViewBag.colorlist[i].Color_id"/>
}
<input type="submit" value="Save" />
}
问题是当提交复选框而不选择第一个时,List<ProdColor> 的值变为Null。那么我应该如何在Controller 获得正确的值。
【问题讨论】:
-
欢迎来到 SO。这个现有的问题对您有帮助吗? stackoverflow.com/questions/220020/…
标签: c# asp.net-mvc asp.net-mvc-4 razor checkbox