I'm working on ASP.NET MVC web application, and I need to submit List<ProdColor>
to Controller
using checkbox
s. Here is my code
Model
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; }
}
Controller
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");
}
View
@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" />
}
The problem is when submitting the checkboxes without selecting the first one, the value of List<ProdColor>
become Null
. So how should I get the correct values at the Controller
.
Aucun commentaire:
Enregistrer un commentaire