Passing multiple checkbox values & dyamically generating textboxes based on checkboxes checked in MVC 4

2.1k Views Asked by At

Using - ASP.NET MVC 4

UI is like -

Select      Product Code      Product Name

Checkbox    Product 1         Apple
Checkbox    Product 2         Banana
Checkbox    Product 3         Grapes

Submit Button

On submit button click i need to validate whether checkbox selected or not. If not, shows message - Please select one product.

If selected, then in the controller, pass the selected Product Code & Name & no. of checkboxes checked to another page

How can we achieve this in MVC 4?

1

There are 1 best solutions below

9
On BEST ANSWER

Firstly, @Html.CheckboxFor(m => m.Checkbox, "Product 1") is assigning "Product 1" as a html attribute and will render <input length="9" type="checkbox" .../> (the length attribute has been added with a value equal the number of characters in the text). Its also creating invalid html because of duplicate id attributes. And the [Required] attribute is pointless (a bool is either true or false and will always be required). Currently you have no relationship between the checkbox and product.

You should create a view model to represent what you want to display

public class ProductVM
{
  public bool IsSelected { get; set; }
  public string Code { get; set; }
  public string Name { get; set; }
}

Controller

public ActionResult Edit()
{
  List<ProductVM> model = new List<ProductVM>()
  {
    new ProductVM() { Code = "Product 1", Name = "Apple" },
    new ProductVM() { Code = "Product 2", Name = "Banana" },
    new ProductVM() { Code = "Product 3", Name = "Grapes"}
  };
  return View(model);
}

[HttpPost]
public ActionResult Edit(List<ProductVM> model)
{
  foreach(ProductVM item in model)
  {
    if (item.IsSelected)
    {
      string code = item.Code;
      string name= item.Name;
    }
  }
}

View

@model List<ProductVM>
@using(Html.BeginForm())
{
  for(int i = 0; i < Model.Count; i++)
  {
    @Html.HiddenFor(m => m[i].Code)
    @Html.HiddenFor(m => m[i].Name)
    @Html.CheckBoxFor(m => m[i].IsSelected)
    @Html.LabelFor((m => m[i].IsSelected, Model[i].Name)
  }
  <input type="submit" />
}

If you want client side validation, you are going to have to write your own validation attribute that implements IClientValitable and write the associated jquery validation methods (but that's the subject of a separate question)