Allow Only Single Checkbox To Be Checked At A Time In Kendo MVC

0
371
Step 1

Create a new MVC Empty Project, using Visual Studio. This example shows how to allow only one item to be allowed to be selected in the grid.

Add new Layout.cshtml into shared folder. Add references of Kendo, CSS and JavaScript into this Layout.cshtml.

<!DOCTYPE html>  
<html>  
    <head>  
        <title>@ViewBag.Title - My Kendo UI MVC Application</title>  
        <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />  
        <link href="@Url.Content("~/Content/kendo/2016.2.504/kendo.common-bootstrap.min.css")" rel="stylesheet" type="text/css" />  
    <link href="@Url.Content("~/Content/kendo/2016.2.504/kendo.mobile.all.min.css")" rel="stylesheet" type="text/css" />  
    <link href="@Url.Content("~/Content/kendo/2016.2.504/kendo.dataviz.min.css")" rel="stylesheet" type="text/css" />  
    <link href="@Url.Content("~/Content/kendo/2016.2.504/kendo.bootstrap.min.css")" rel="stylesheet" type="text/css" />  
    <link href="@Url.Content("~/Content/kendo/2016.2.504/kendo.dataviz.bootstrap.min.css")" rel="stylesheet" type="text/css" />  
    <script src="@Url.Content("~/Scripts/kendo/2016.2.504/jquery.min.js")"></script>  
    <script src="@Url.Content("~/Scripts/kendo/2016.2.504/angular.min.js")"></script>  
    <script src="@Url.Content("~/Scripts/kendo/2016.2.504/jszip.min.js")"></script>  
    <script src="@Url.Content("~/Scripts/kendo/2016.2.504/kendo.all.min.js")"></script>  
    <script src="@Url.Content("~/Scripts/kendo/2016.2.504/kendo.aspnetmvc.min.js")"></script>  
</head>  
    <body>  
        <header>  
            <div class="content-wrapper">  
                <div class="float-left">  
                    <p class="site-title" style="margin-left: 30%;">@Html.ActionLink("www.CoderFunda.com", "Index", "Home")</p>  
                </div>                  
            </div>  
        </header>  
        <div id="body">  
            @RenderSection("featured", required: false)  
            <section class="content-wrapper main-content clear-fix">  
                @RenderBody()  
            </section>  
        </div>  
  
        <footer>  
            <div class="content-wrapper">  
                <div class="float-left">  
                    <p>© @DateTime.Now.Year - My Telerik MVC Application</p>  
                </div>  
            </div>  
        </footer>  
    </body>  
</html>

Step 2

Now, add one model into a Model folder & give name as Company. Add some properties into it.

 

public class Company  
{  
public int Id { get; set; }  
public string Name { get; set; }  
public bool IsValid { get; set; }  
}

Add HomeController in Controller. There is one action method, which will bind the data to the grid, using model.

 

public class HomeController : Controller  
  {  
      public ActionResult Index()  
      {  
  
          return View();  
      }  
  
      public ActionResult BindGrid([DataSourceRequest]DataSourceRequest request)  
      {  
          try  
          {  
              List<Models.Company> objCmp = new List<Models.Company>();  
              objCmp.Add(new Models.Company() { Id = 1, Name = "Rupesh Kahane", IsValid = false });  
              objCmp.Add(new Models.Company() { Id = 2, Name = "Vithal Wadje", IsValid = false });  
              objCmp.Add(new Models.Company() { Id = 3, Name = "Jeetendra Gund", IsValid = false });  
              var lst = objCmp.ToList();  
  
              DataSourceResult result = lst.ToDataSourceResult(request, p => new Models.Company  
              {  
                  Id = p.Id,  
                  Name = p.Name,  
                  IsValid = p.IsValid,  
              });  
              return Json(result, JsonRequestBehavior.AllowGet);  
          }  
          catch (Exception ex)  
          {  
              var errorMsg = ex.Message.ToString();  
              return Json(errorMsg, JsonRequestBehavior.AllowGet);  
          }  
      }  
  }

 

Step 3

Add View by right clicking on Action Method Index, which will show a grid with the details. In our grid, I am going to add a template to show a checkbox for the property of IsValid.

Now, add a JavaScript code into a document.ready function for onchange event of grid checkbox, which will uncheck all checkboxes & check only single checkbox on which an event is fired.

@using System.Web.Optimization  
@using Kendo.Mvc.UI  
@using Kendo.Mvc.Extensions  
@{  
    Layout = "~/Views/Shared/_Layout.cshtml";  
}  
  
<div style="width:450px;">  
    @(Html.Kendo().Grid<Grid.Models.Company>()  
        .Name("DetailGrid")  
        .Columns(columns =>  
        {  
            columns.Bound(p => p.Id).Title("Id").Width(2).Filterable(false);  
            columns.Bound(p => p.Name).Title("Name").Width(10).Filterable(false);  
            columns.Bound(p => p.IsValid).ClientTemplate("# if(IsValid==true){#" + "<input  type='checkbox' checked='checked' id='chboxSelect' class='checkBox' />" + "#}else{#" + "<input type='checkbox' id='chboxSelect' class='checkBox'/>" + "#}#").Title("Valid").Width(5).Filterable(false);  
        })  
            .Scrollable()  
            .Filterable(ftp => ftp.Mode(GridFilterMode.Row))  
            .Resizable(resize => resize.Columns(true))  
            .Pageable(x => x.PageSizes(new List<object> { 10, 20, 100, 200, 500, "all" }).Refresh(true))  
            .HtmlAttributes(new { style = "height: 100%" })  
            .DataSource(dataSource => dataSource  
            .Ajax()  
            .Model(model => model.Id(p => p.Id))  
            .ServerOperation(false)  
            .Read(read => read.Action("BindGrid", "Home"))  
     )  
    )  
</div>  
  
<script>  
    $(document).ready(function () {  
        $("#DetailGrid").on("change", "input.checkBox", function (e) {  
            var currentEventFired = $(this).is(":checked");  
            $("input.checkBox", "#DetailGrid").prop("checked", false);  
            $(this).prop("checked", currentEventFired);  
        });  
    });  
</script>

Step 4

Now, run the application. In the controller, I have assigned False values to IsValid property. Now, I am selecting checkbox of  the first one and our result will be, as shown below.

Now, click another checkbox, so first checkbox will get unchecked & current one will get checked.

Summary

In this article, you learnt the basics of how to allow only single checkbox to be checked at a time in Kendo MVC.

 

SHARE
Previous articleMultiple Ways To Bind Data To Kendo Grid In MVC
Next articleASP.NET MVC Ajax.BeginForm AjaxOptions OnSuccess, OnFailure
Currently working as a Software Engineer in MNC company. Having working knowledge of technologies like ASP.NET, MVC 5.0, C#, Kendo UI, KnockOut.Js, JavaScript, SQL Server 2012, HTML5 etc. He had conducted more than 80 hands on Seminars, Workshops for College, Schools and Training Institutes. He blog at http://www.c-sharpcorner.com/members/rupesh-kahane2

LEAVE A REPLY

Please enter your comment!
Please enter your name here