1

My issue today revolves around implementing a checkboxlist and getting the item selected in MVC 5. Here's the issue i am having:

EmployeeViewModel viewModel = new EmployeeViewModel { data =  
manager.getEmployeeData() };
return View(viewModel);

I have a dropdownlist in my Main View and in order to populate it with the data from the array, i created a View Model, which then gets sent into the view, as shown below:

Public class EmployeeViewModel {
    public MyEmployees[] data {get; set;};
}

The issue is, unfortunately, the data array does not have a boolean isSelected property but has properties like employeeName and Id. So ultimately, my question is, how would i implement a checkbox list which allows for multiple selections AND to select all employees as well as allowing me to know which employee got selected or was not selected. I cannot use bootstrap or anything like that so have to implement it using HTML helpers or C#/ASP.NET etc. Thanks for all the help.

Edit: Sorry for not making this clear earlier, i want this checkbox list to appear within a dropdownlist. So basically, upon clicking the dropdown, you have items with checkboxes next to them.

4
  • Your editing data, so always use a view model. And view models do NOT contain data models - create an EmployeeVM containing bool IsSelected plus the other properties of Employee that you want in the view Commented Jan 25, 2018 at 21:34
  • @StephenMuecke how would i get this checkboxlist to show up within a dropdownlist and function correctly? I'm basing this question after taking into account the information shyju provided below. Commented Jan 26, 2018 at 15:02
  • You cant unless you use a jQuery plugin Commented Jan 26, 2018 at 21:16
  • Alright @StephenMuecke thank you for letting me know :) Commented Jan 29, 2018 at 14:35

2 Answers 2

7

View models are models specific to views. So if your view requires selecting records, create a view model which has an IsSelected property and you can use the CheckBoxFor helper to render check boxes for each of the items in your collection.

You can use editor templates to send the list of checkbox selections to server.

So I would create a view model which represents the selection.

public class EmployeeSelection
{
    public bool IsSelected { set; get; }
    public string Name { set; get; }
    public int Id { set; get; }
}

and add a list of this type to our page view model

public class EmployeeViewModel
{
    public List<EmployeeSelection> EmployeeSelections { set; get; }

    // Other properties needed for the page also goes here. 
    // ex: Let's add a Location property
    public string Location { set;get;} 
}

Now in your GET action, populate the EmployeeSelections property and send to the view.

public ActionResult Create()
{
   var vm=new EmployeeViewModel();
   vm.EmployeeSelections = manager.getEmployeeData()
                                  .Select(a => new EmployeeSelection() {
                                        Id = a.Id,
                                        Name = a.Name})
                                  .ToList();
   return View(vm);
}

Next step is creating an editor template. Create a new razor view called EmployeeSelection.cshtml under ~/Views/Shared/EditorTemplates or ~/Views/{YourControllerName}/EditorTemplates. Have this editor template razor strongly typed to the EmployeeSelection view model. Inside this view, you can use the CheckBoxFor helper method to render checkbox for the model passed to this template. We will also keep the Id property value inside a hidden input.

@model EmployeeSelection
<div>
    @Model.Name
    @Html.CheckBoxFor(a=>a.IsSelected)
    @Html.HiddenFor(a=>a.Id)
</div>

Now in your main view, which is strongly typed to EmployeeViewModel, we can use the EditorFor helper method for the EmployeeSelections property of that page's model(EmployeeViewModel object)

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.LabelFor(a=>a.Location)
    @Html.TextBoxFor(a=>a.Location)

    <label>Select employees</label>
    @Html.EditorFor(a=>a.EmployeeSelections)

    <button type="submit">Save</button>
}

This will render the names and checkboxes associated to it (along with the hidden input element for Id). When user submits the form, in your HTTP post action method, you can check the EmployeeSelections and filter that to get the subset which has the IsSelected property set to true

[HttpPost]
public ActionResult Index(IndexVm model)
{
     var selected = model.EmployeeSelections.Where(a=>a.IsSelected).ToList();
    // If you want Id's select that
    var ids = selected.Select(g => g.Id);

    // to do : return something
}
Sign up to request clarification or add additional context in comments.

5 Comments

Wow @shyju, thank you for the very detailed explanation. Your explanation was immaculate. My only question is, how would i populate a dropdown list with a checkbox next to each of the employee names? So basically, when you click on the dropdownlist, it shows multiple employee names, each with checkboxes next to tohem.
By default there is no such HTML controls! you probably need some client side plugins to get this effect
so there is no way for me to use Html.DropDownlistFor instead of Editor For to render the EmployeeSelection model?
DropDownlistFor renders a SELECT element which has a list of options user can select. There is no native HTML control which has checkboxes inside SELECT element.
I see, so without any sort of custom plugin, in terms of ASP.NET MVC, i cannot have a checkbox item based drop down list?
0

I would give a devextreme example that works

<div class="list-api-demo">
<div class="widget-container">
    @(Html.DevExtreme().DropDownBox()
.ID("dropDownBox")
.DataSource(d => d.Mvc())
.Value("Name")
.ContentTemplate(@<text>
        @(Html.DevExtreme().List()
        .ID("simpleList")
        .Height(400)
        .DataSource(d => d.Mvc().Controller("YourControler").LoadAction("Get").Key("ID"))
        .AllowItemDeleting(false)
        .ShowSelectionControls(true)
        .SelectionMode(ListSelectionMode.Multiple)
        .OnSelectionChanged("list_updateSelection")
        .ItemTemplate(new JS("empList")))</text>))
</div>

<script>
    var list_updateSelection = function (e) {
        var selectedItems = e.component.option("selectedItems");
        var selectedTexts = $.map(selectedItems, function (item) {
            return item.Text;
        });
        $("#selectedItems").text(selectedTexts.join(", "));
    };
</script>

<script>
    function empList(itemData, itemIndex, itemElement) {
        itemElement
            .addClass("my-custom-style")
            .append(
                $("<span>").text(itemData.Name)
            );
    }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.