Kendo Ui Grid Razor Set Editable Based on Value on Read

  • Updated date Dec 04, 2020
  • 228.8k
  • 4

In this article, we will learn how to bind data to Kendo Grid in MVC using multiple ways.

Introduction

Many times, while working with Grid, we need to show the result into a GridView in different situations.

What is Kendo Grid?

The Kendo UI Grid is a powerful widget that allows you to visualize and edit data via its table representation. It provides many options, such as paging, sorting, filtering, grouping, and editing, which determine the way data is presented and manipulated.

The Grid tin be bound to local or remote data by using the Kendo UI DataSource component.

Scenario I Bind data to Kendo Grid by using AJAX Read action method.

Scenario II Change the datasource on alter outcome of any HTML controls.

Scenario I

Commonly, a developer can bind the data to Grid by using AJAX Read method.

This read method is ActionResult method in MVC which will return JSON DataSourceResult & direclty bind the data to Grid.

Annotation

Besides, the developer can pass parameters to this read method. Suppose below is our read method.

  1. Read(read => read.Activity( "BindGrid" , "Dwelling house" ).Data( "SortByCompanyId" ))

In the in a higher place line, my JavaScript function name is SortByCompanyId which volition render company id. On that basis, we can pass parameter to our activity method in Controller.

  1. public  ActionResult BindGrid([DataSourceRequest]DataSourceRequest request, string  companyId)
  2. {
  3. }

Our JavaScript role is like the following.

  1. <script type= "text/javascript" >
  2. role  SortByCompanyId() {
  3. var  cId = 25;
  4. render  {
  5.             companyId: cId
  6.         }
  7.     }
  8. </script>

Step 1Create a Model, give it a name as Company, and declare some properties into it.

  1. public class  Company
  2. {
  3. public int  Id { get ; prepare ; }
  4. public string  Name { become ; fix ; }
  5. public int ? CompanyId { get ; set ; }
  6. }

Footstep 2Now, create a Controller, requite it proper noun equally HomeController. In this, create a action method as Index() which will return a View. On this View, write some lawmaking to bind data into the Grid View by using the higher up Model.

  1. @model Grid.Models.Company
  2. @using System.Web.Optimization
  3. @using Kendo.Mvc.UI
  4. @using Kendo.Mvc.Extensions
  5. @{
  6. Layout  = "~/Views/Shared/_Layout.cshtml" ;
  7. }
  8. < div way = "width:60%;pinnacle:100%" >
  9.     @(Html.Kendo().Grid< Grid.Models.Visitor > ()
  10.         .Proper noun("BindGridUsingRead")
  11.         .Columns(columns  = >
  12.         {
  13.             columns.Bound(p  = >  p.Id).Width(15).Title("Sr. No.").Filterable(false);
  14.             columns.Bound(p  = >  p.Proper noun).Title("Proper name").Width(xxx).Filterable(false);
  15.             columns.Bound(p  = >  p.CompanyId).Championship("Company Id").Width(fifteen).Filterable(false);
  16.             })
  17.            .Scrollable()
  18.            .Pageable(x  = >  ten.PageSizes(new Listing < object >  { 10, xx, 100, 200, 500, "all" }).Refresh(true))
  19.             .Filterable(ftp  = >  ftp.Mode(GridFilterMode.Row))
  20.             .Resizable(resize  = >  resize.Columns(true))
  21.             .HtmlAttributes(new {mode  = "superlative: 100%"  })
  22.             .Selectable()
  23.             .DataSource(dataSource  = >  dataSource
  24.             .Ajax()
  25.             .Model(model  = >  model.Id( p  = >  p.Id))
  26.             .ServerOperation(fake)
  27.             .Read(read  = >  read.Action("BindGrid", "Home"))
  28.      )
  29.     )
  30. </ div >

Stride 3In Controller, write method which will bind the data to Grid past using Ajax Read activity method. Now, write some action methods named every bit BindGrid (to bind the JSON information to Grid). I am going to bind some hard coded values past using action method GetGridData() using Company model which will render IEnumerable Listing.

  1. public  ActionResult Index()
  2. {
  3. return  View();
  4. }
  5. public  ActionResult BindGrid([DataSourceRequest]DataSourceRequest asking)
  6. {
  7. try
  8.     {
  9. decimal  companyId = 0;
  10.         List<Models.Company> lst =new  List<Models.Company>();
  11.         lst = GetGridData(Convert.ToInt32(companyId)).ToList();
  12.         DataSourceResult result = lst.ToDataSourceResult(request, p =>new  Models.Company
  13.         {
  14.             Id = p.Id,
  15.             Name = p.Name,
  16.             CompanyId = p.CompanyId,
  17.         });
  18. return  Json(event, JsonRequestBehavior.AllowGet);
  19.     }
  20. take hold of  (Exception ex)
  21.     {
  22.         var errorMsg = ex.Message.ToString();
  23. return  Json(errorMsg, JsonRequestBehavior.AllowGet);
  24.     }
  25. }
  26. public  IEnumerable<Models.Company> GetGridData( decimal  companyId)
  27. {
  28.     List<Models.Company> objCmp =new  List<Models.Company>();
  29.     List<Models.Visitor> listCompany =new  List<Models.Company>();
  30.     objCmp.Add(new  Models.Visitor() { Id = i, Name = "Rupesh Kahane" , CompanyId = 20 });
  31.     objCmp.Add together(new  Models.Visitor() { Id = 2, Proper name = "Vithal Wadje" , CompanyId = xl });
  32.     objCmp.Add(new  Models.Company() { Id = iii, Name = "Jeetendra Gund" , CompanyId = 30 });
  33.     objCmp.Add(new  Models.Company() { Id = 4, Proper noun = "Ashish Mane" , CompanyId = fifteen });
  34.     objCmp.Add(new  Models.Company() { Id = 5, Name = "Rinku Kulkarni" , CompanyId = 18 });
  35.     objCmp.Add(new  Models.Company() { Id = 6, Name = "Priyanka Jain" , CompanyId = 22 });
  36. if (companyId > 0)
  37.     {
  38.         listCompany = objCmp.ToList().Where(a => a.CompanyId <= companyId).ToList();
  39. return  listCompany.AsEnumerable();
  40.     }
  41. return  objCmp.ToList().AsEnumerable();
  42. }

Step 4Here is the issue after running our solution.




Scenario II

While working with html controls or forms, there are some situations, similar we need to bind the data to Grid on change event of controls or we need to employ some custom filters, on search button click consequence, nosotros are applying these filters that modify the datasource on change issue of any html control.

Notation

In that location is a built-in functionality likewise to filter Grid data from column values. Here, we are using custom filters.

Suppose, the user entered some integer value & we demand the data where company id is less than input value in on change event of control. So we have one textbox & will write on change consequence code into a javascript past using ship.options.read method. Nosotros are passing read method URL & input value to out action method.

Step 1As I explained in scenario I, we are adding only 1 textbox &JS file which contains alter event function to our View. Add together some JavaScript code above this which volition incorporate bind grid method equally -

  1. <script type= "text/javascript" >
  2. var  gridObject;
  3. var  readURL = new  Array();
  4.     readURL[0] ="/Home/BindGrid" ;
  5.     readURL[i] ="/Home/BindGridOnSearch?companyId=" ;
  6. </script>

Now, our View folio will look similar the following.

  1. @model Grid.Models.Company
  2. @using System.Web.Optimization
  3. @using Kendo.Mvc.UI
  4. @using Kendo.Mvc.Extensions
  5. @{
  6. Layout  = "~/Views/Shared/_Layout.cshtml" ;
  7. }
  8. < script type = "text/javascript" >
  9.     var gridObject;
  10.     varreadURL  = new  Array();
  11.     readURL[0] = "/Home/BindGrid";
  12.     readURL[1] = "/Domicile/BindGridOnSearch?companyId =";
  13. </ script >
  14. < div >
  15. < div grade = "box-header with-border" >
  16. < div course = "col-xs-12" >
  17. < div class = "col-xs-iv martop" style = "text-align:right;width:22%" >
  18.                 @(Html.Kendo().TextBoxFor(model  = >  model.CompanyId)
  19.                     .Name("CompanyId")
  20.                     .HtmlAttributes(new {placeholder  = "Search Past Company Id" , @ autocomplete  = "off" , @ class  = "col-sm-12" , manner  = "width:100%" , maxlength  = 200  })
  21.                 )
  22. </ div >
  23. </ div >
  24. </ div >
  25. </ div >
  26. < br />
  27. < div mode = "width:threescore%;superlative:100%" >
  28.     @(Html.Kendo().Grid< Grid.Models.Company > ()
  29.         .Name("BindGridUsingRead")
  30.         .Columns(columns  = >
  31.         {
  32.             columns.Leap(p  = >  p.Id).Width(xv).Title("Sr. No.").Filterable(false);
  33.             columns.Bound(p  = >  p.Proper name).Title("Name").Width(30).Filterable(false);
  34.             columns.Jump(p  = >  p.CompanyId).Championship("Company Id").Width(fifteen).Filterable(imitation);
  35.             })
  36.            .Scrollable()
  37.            .Pageable(x  = >  x.PageSizes(new List < object >  { 10, 20, 100, 200, 500, "all" }).Refresh(true))
  38.             .Filterable(ftp  = >  ftp.Mode(GridFilterMode.Row))
  39.             .Resizable(resize  = >  resize.Columns(true))
  40.             .HtmlAttributes(new {style  = "height: 100%"  })
  41.             .Selectable()
  42.             .DataSource(dataSource  = >  dataSource
  43.             .Ajax()
  44.             .Model(model  = >  model.Id( p  = >  p.Id))
  45.             .ServerOperation(false)
  46.             .Read(read  = >  read.Action("BindGrid", "Domicile"))
  47.      )
  48.     )
  49. </ div >
  50. < script src = "~/Scripts/Custom/Home.js" > </ script >

Pace twoAt present, write code on change event of textbox into JavaScript Domicile.js file. In our JS file on windows.load method, nosotros tin get information of Filigree into a our global variable.

  1. $(window).load( function  () {
  2.     gridObject = $("#BindGridUsingRead" ).data( "kendoGrid" );
  3. });
  4. $(document).ready(part  () {
  5.     $('#CompanyId' ).on( 'change' , function  () {
  6. var  cmpId = $( "input[id='CompanyId']" ).val();
  7.         gridObject.dataSource.send.options.read.url = readURL[1] + cmpId;
  8.         gridObject.dataSource.read();
  9.     });
  10. });

Step iiiWrite some code into Controller against these read methods.

  1. public  ActionResult BindGridOnSearch([DataSourceRequest]DataSourceRequest request, string  companyId)
  2. {
  3. try
  4.     {
  5.         List<Models.Company> list =new  List<Models.Company>();
  6.         list = GetGridData(Convert.ToInt32(companyId)).ToList();
  7.         DataSourceResult result = list.ToDataSourceResult(request, p =>new  Models.Company
  8.         {
  9.             Id = p.Id,
  10.             Name = p.Name,
  11.             CompanyId = p.CompanyId,
  12.         });
  13. return  Json(upshot, JsonRequestBehavior.AllowGet);
  14.     }
  15. catch  (Exception ex)
  16.     {
  17.         var errorMsg = ex.Message.ToString();
  18. return  Json(errorMsg, JsonRequestBehavior.AllowGet);
  19.     }
  20. }

Step 4Here is the result after running our solution (if we enter 25 into input box).

Summary

In this article, yous learned the nuts of how to demark data to Kendo Grid in MVC using multiple methods.

Kendo Ui Grid Razor Set Editable Based on Value on Read

Source: https://www.c-sharpcorner.com/article/multiple-ways-to-bind-data-to-kendo-grid-in-mvc/

0 Response to "Kendo Ui Grid Razor Set Editable Based on Value on Read"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel