我正在研究ASP.NET MVC Web應用程序,並且需要使用checkbox
來提交List<ProdColor>
到Controller
。這裏是我的代碼如何在ASP.NET MVC中正確提交複選框值給控制器
型號
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" />
}
的概率lem是在提交複選框時未選擇第一個一,List<ProdColor>
的值變爲Null
。那麼我應該如何在Controller
上得到正確的值。
歡迎來到SO。這個存在的問題對你有幫助嗎? http://stackoverflow.com/questions/220020/how-to-handle-checkboxes-in-asp-net-mvc-forms?rq=1 – Fabske