vendredi 27 mars 2015

Model Binding with Checkboxes in MVC

I have a "Product Create" page and I need to add a Color porperty to it. One product might have more than one color, So I have written a seperate Color model and a ProductColorRelations model. With these models, I can bind many colors to a product.



public class ProductDetailViewModel
{
public AY_PRODUCT product { get; set; }
public List<AY_COLOR> colors { get; set; }
}


// ACTION ON LOAD
public ActionResult ProductsCreate()
{
ProductDetailViewModel mdl = new ProductDetailViewModel();
mdl.product = new AY_PRODUCTS();

mdl.colors = (from g in db.AY_COLORS select g).ToList();

return View(mdl);
}

[HttpPost]
public ActionResult ProductsCreate(ProductDetailViewModel prod_)
{
if (ModelState.IsValid)
{
db.AY_PRODUCTS.Add(prod_.product);
db.SaveChanges();
int ProductId= prod_.product.ID;

//HOW CAN I GET THE VALUES OF SELECTED COLORS HERE?

return RedirectToAction("ProductsCreate");
}
else
{
return View(prod_);
}
}


and here is my view which I couldnt complete.



<% foreach (var item in mdl.colors) { %>
<%: Html.CheckBox( <!-- what exactly ?????? -->) %>
<% } %>


How should I write the view and Action to get the values of selected checkboxes. Please help...





Aucun commentaire:

Enregistrer un commentaire