1

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...

Arif YILMAZ
  • 5,754
  • 26
  • 104
  • 189
  • 2
    What is typeof `AY_COLOR`? Does it have a boolean property (say `bool IsSelected`) to bind a checkbox to? If not you should be using a view model and a `for` loop (not `foreach`) to generate the controls –  Mar 27 '15 at 07:06
  • AY_COLOR has ID and COLOR_NAME properties. I have a different Database Table ProductColorRelations which will store the relations between product and olors, since a product can have more than one color – Arif YILMAZ Mar 27 '15 at 07:08
  • 3
    I would recommend you also have a view model for the colors, with properties `ID`, `Name` and `IsSelected`. You can then bind your checkboxes in a `for` loop using `@Html.CheckBoxFor(m => m.Colors[i].IsSelected)` and when you post back, check the value of `IsSelected` –  Mar 27 '15 at 07:15
  • That makes sense. Thanks. But how am I supposed to bind the View and Model? Can you help me with that? – Arif YILMAZ Mar 27 '15 at 07:16
  • 2
    You just need to map the model to the view model and vice-versa on post back. Tools such as [automapper](https://github.com/AutoMapper/AutoMapper) can make it easy, but you could simply use something like `mdl.colors = (from g in db.AY_COLORS select g).Select(c => new ColorVM() { ID = c.ID, Name = c.COLOR_NAME }).ToList();` –  Mar 27 '15 at 07:23
  • I'm not sure if this is too late, but I was able to make something similar work and perhaps it will help. http://stackoverflow.com/a/36875727/943746 – niki b Apr 27 '16 at 19:07

0 Answers0