Tuesday, August 19, 2014

mvc checkboxlist


//Set up a viewmodel MyViewModel to contain the following

        [DisplayName("Available Products")]
        public IList AvailableProducts { get; set; }
        public IList SelectedProducts { get; set; }

        public PostedProducts PostedProducts { get; set; }



//The definition of ProductDropdownItemViewModel and PostedProducts are:

    public class PostedProducts
    {
        public int[] ProductIds { get; set; }
    }

    public class ProductDropdownItemViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }        
    }


//In your controller method populate the above viewmodel

  e.g. 
                MyViewModel.AvailableProducts = db.Products
                .Select(p => new ProductDropdownItemViewModel 
            {
                Id = p.Id,
                Name = p.Name
            }).ToList();


//In your view display the checkbox list this way

  e.g. the postback method name is Edit

     @model MyViewModel
     @using (Html.BeginForm("Edit", FormMethod.Post, new { enctype = "multipart/form-data" }))
     {
        @Html.CheckBoxListFor(x => x.PostedProducts.ProductIds,
                      x => x.AvailableProducts,
                      x => x.Id,
                      x => x.Name,
                      x => x.SelectedProducts,
                      MvcCheckBoxList.Model.Position.Vertical)
     }


//In your postback method Edit use the following code to retrieve your selected items


       public ActionResult Edit(PostedProducts postedProducts)
       {

                foreach (var id in postedProducts.ProductIds)
                {
                     //do whatever you like with the selected product id
                }

       }

No comments: