So my problem goes like this,
I have two lists
LIST A contains.
- Item 1
- Item 2
- Item 3
- Item 4
- Item 5
And List B Contains
- Item 1
- Item 2
- Item 3
- Item 4
- .....
- ....
- Item 10
All i want to do is Generate Checkboxes dynamically in MVC Razor View for all the items in B, and of those checkboxes, check(select) all the checkboxes for all the items in A.
As A will always be a subset of B.
And then a user can check-uncheck any boxes, and those values can be passed to controller for Saving purposes. The List A will be updated with new values, that user selects.
Any Help ?
UPDATE 1:
I am able to get all the items in Model.CheckboxSelections in view. I don't want to use a partial view. I am trying something like following, but something is still missing.
@for (int i = 0; i < Model.CheckboxSelections.Count; i++)
{
@Html.CheckBox(Model.CheckboxSelections[i].Sku.ToString(), Model.CheckboxSelections[i].IsChecked.ToString())
}
With a certain risk of repeating myself I would start my answer with the following sentence:
As always in ASP.NET MVC application you should use a view model.
So:
public class MyViewModel
{
public string Name { get; set; }
public bool IsChecked { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
// Those are your domain models
// they could come from a database or something
var listA = new[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
var listB = new[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10" };
// Now let's map our domain model to our view model
var model = listB.Select(x => new MyViewModel
{
Name = x,
IsChecked = listA.Contains(x)
});
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> model)
{
var selectedItems = model.Where(x => x.IsChecked);
var format = string.Join(",", selectedItems.Select(x => x.Name));
return Content("Thank you for selecting " + format);
}
}
then a corresponding view (~/Views/Home/Index.cshtml
):
@model IEnumerable<MyViewModel>
@using (Html.BeginForm())
{
@Html.EditorForModel()
<button type="submit">OK</button>
}
and finally the corresponding editor template which will be automatically rendered for each element of the model collection (~/Views/Home/EditorTemplates/MyViewModel.cshtml
):
@model MyViewModel
<div>
@Html.HiddenFor(x => x.Name)
@Html.LabelFor(x => x.IsChecked, Model.Name)
@Html.CheckBoxFor(x => x.IsChecked)
</div>
and the rendered result (as seen by my Chrome browser) looks like this:
See how easy it is when you use view models?