Search code examples
c#jqueryasp.net-mvchtml-helperjquery-ui-multiselect

MVC Html Helper MultiSelect CheckBox


        public ActionResult Edit(int? id)
    {
        ViewBag.Role = new SelectList((from t in db.Roles where t.RoleID != 1 && t.RoleID != 2 select t), "RoleID", "RoleName");

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        User user = db.Users.Find(id);

        if (user == null)
        {
            return HttpNotFound();
        }

        return View(user);
    }

The ViewBag.Role is to generate all the Roles Value into the multiselect checkbox.

        <div class="form-group">
        @Html.Label("Roles", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("Role", null, htmlAttributes: new { @multiple = "multiple", @class = "form-control" })
        </div>
    </div>

<script type="text/javascript">
$(function () {
    $('#Role').multiselect({
        includeSelectAllOption: true
    });
});

Basically the MultiSelect CheckBox look like the following image.

enter image description here

Here is my question, how do i precheck the roles that the user already have ?? For example, x user have a role Manager so during edit page Manager checkbox will be checked.


Solution

  • You can do it like this:

    $('select').multiselect({includeSelectAllOption: true});
    
    // Get your data
    var userRoles="1,3"; // You can use a ViewBag like ViewBag.UserRoles for roles of user
    
    // Split data by ","
    var userRolesArray=userRoles.split(",");
    
    // Set dataArray
    $("select").val(userRolesArray);
    
    // Refresh for cheking default values
    $("select").multiselect("refresh");
    

    You can use a ViewBag like ViewBag.UserRoles for roles of user and fill it in your Action.

    Online demo (jsfiddle)