How to detect Kendo Grid MVC initial binding on controller - asp.net-mvc

I have a Kendo grid :
#(Html.Kendo().Grid<MyVm>().Name("grid").Columns(columns =>
...
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.Id))
.Read(read => read.Action("List", "MyController", new { id = Model.Id }).Type(HttpVerbs.Get)))
On my controller I have :
public JsonResult List([DataSourceRequest] DataSourceRequest request, int id)
{
//if (FIRST/INITIAL LOADING) ?????
...
}
How can I check on controller if its the initial loading/binding?
Thanks

You can add a Data method to your read call which will use a js function that will return a global variable that's set true onLoad and sets it false.
Then every time you read data it will send IsFirstRead parameter
.Read(read => read.Action("List", "MyController", new { id = Model.Id }).Type(HttpVerbs.Get)).Data("isFirstRead"))
function isFirstRead() {
if (firstTime) {
firstTime = false;
return true;
}
else
return false;
}
public JsonResult List([DataSourceRequest] DataSourceRequest request, int id, bool isFirstTime)
{
//if (isFirstTime) ?????
...
}
GoodLuck

Related

Kendo Grid - ASP MVC is not displaying the drop down list

I'm developing a project with ASP MVC 5, Kendo UI, and some layers, but I'm struggling with how to display the drop-down list inside of an editable Grid, I followed this example:
Grid Editing / custom editor
However, I'm having serious issues because the drop-down list never appears, it's displaying two text boxes.
Also, if I run the Foreign Key column example:
Grid / ForeignKey column
I have a different result with a numeric up-down:
Besides, I tested this example from StackOverflow and the result is either two textboxes or the numeric up-down (it depends if I bound the column or I use the foreign key column):
dropdownlist in kendo grid not working
This is my code, in the Business Layer, I have these classes in order to return the Categories from the database:
using Test.DB.Operations;
using System.Collections.Generic;
using System.Linq;
namespace Test.Business
{
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
}
public class CategoryData
{
public static List<Category> GetCategories()
{
var catData = DatabaseService.GetEntities<DB.Category>().ToList();
return (from cData in catData select new Category() { ID = cData.ID, Name = cData.Name }).ToList();
}
}
}
Later, in my MVC Layer, the Controller populates the view with some methods like these ones:
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Test.Business;
using Test.Classes;
using Test.MVC.Classes;
using Test.MVC.Models;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace Test.MVC.Controllers
{
public class OrganizationDetailsController : Controller
{
public ActionResult Index(string ID)
{
PopulateCategories();
if (!string.IsNullOrEmpty(ID))
{
var model = new OrganizationsModel();
try
{
model.hasError = false;
model.messageBox = null;
}
catch (Exception ex)
{
model.hasError = true;
model.messageBox = new Tuple<string, string>("Error", "Please report it to the team");
}
return View(model);
}
else
{
return View();
}
}
public ActionResult OrganizationDetails_Read([DataSourceRequest]DataSourceRequest request, string ID)
{
try
{
var data = OrganizationDetailsData.GetOrganizationDetails(ID);
DataSourceResult result = data.ToDataSourceResult(request);
return Json(result);
}
catch (Exception ex)
{
return null;
}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrganizationDetails_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]<OrganizationDetails> oDetails)
{
return null;
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrganizationDetails_Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<OrganizationDetails> oDetails)
{
return null;
}
private void PopulateCategories()
{
var dataContext = CategoryData.GetCategories();
ViewData["categories"] = dataContext;
ViewData["defaultCategory"] = dataContext[0];
}
}
}
The Model looks like this:
using Test.Business;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Test.MVC.Models
{
public class OrganizationsModel
{
public Tuple<string, string> messageBox;
public bool hasError;
}
}
Finally, in the View, I have this code for the Kendo Grid:
#(Html.Kendo().Grid<Test.Business.OrganizationDetails>()
.Name("gridDetails")
.Columns(columns =>
{
columns.Bound(b => b.Name);
columns.Bound(b => b.NumberOfEmployees);
//columns.ForeignKey(p => p.CategoryID, (System.Collections.IEnumerable)ViewData["categories"], "ID", "Name").Title("Categories").EditorTemplateName("dropdownTemplate");
columns.Bound(b => b.Category).ClientTemplate("#=Category.Name#");
columns.Bound(p => p.Telephone);
columns.Bound(p => p.Address);
})
.ToolBar(toolBar =>
{
toolBar.Create();
toolBar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.ID);
model.Field(p => p.ID).Editable(false);
model.Field(p => p.Category).DefaultValue(ViewData["defaultCategory"] as Test.Business.Category);
})
.PageSize(20)
.Read(read => read.Action("OrganizationDetails_Read", "OrganizationDetails").Data("LoadParams"))
.Create(create => create.Action("OrganizationDetails_Create", "Grid"))
.Update(update => update.Action("Organization_Update", "Grid"))
)
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
)
<input type="hidden" id="orgID" value="1" />
<script id="dropdownTemplate" type="text/x-kendo-template">
#(Html.Kendo().DropDownListFor(m => m)
.Name("myDropDown")
.DataValueField("ID")
.DataTextField("Name")
.BindTo((System.Collections.IEnumerable)ViewData["categories"])
)
</script>
<script type="text/javascript">
function error_handler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
function LoadParams() {
var id = $("#orgID").val();
return { ID: id }
}
</script>
However, it's never working as it should be. Does anyone have experience this issue? And how did you manage it? Thanks for your ideas.
For the ForeignKey() implementation:
you have to put the "dropdownTemplate" in a cshtml file in Views/Shared/EditorTemplates. You cannot use a x-kendo-template because you are not using javascript initialization...you are using the razor helpers. What is likely happening to your is that you are specifying an non-existent EditorTemplate(no cshtml in Shared/EditorTemplates) so it just breaks.
Or, you can leave off the EditorTemplateName() altogether and Kendo will automatically use the EditorTemplate in Views/Shared/EditorTemplates/GridForeignKey.cshtml.
For the "ClientTemplate" implementation:
If you take a look at the full source code for the "Grid Editing / custom editor" example(in the examples that get installed with Kendo MVC), the EditorTemplate is specified using a UIHint on the model.
i.e. (using your classnames)
public class OrganizationDetails
{
...
[UIHint("ClientCategory")]
public CategoryViewModel Category {get; set;}
}
Then there must be a ClientCategory.cshtml file in Views/Shared/EditorTemplates that contains the razor for your editor implementation.
In the Kendo examples, ClientCategory.cshtml contains:
#model Kendo.Mvc.Examples.Models.CategoryViewModel
#(Html.Kendo().DropDownListFor(m => m)
.DataValueField("CategoryID")
.DataTextField("CategoryName")
.BindTo((System.Collections.IEnumerable)ViewData["categories"])
)

KendoUI for ASP.NET MVC duplicates rows

KendoUI for ASP.NET MVC 2016.1.412 grid duplicating data at any update or destroy action. If you click Destroy command it call CREATE action for 10 (ten) times. So if I got 1 row after I destroy it I got 11 row of same data (different ID).
View is like this
#(Html.Kendo().Grid<CETSchoolERP.ViewModels.Administration.StudentsViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.FirstName);
columns.Bound(p => p.LastName).Width(100);
columns.Bound(p => p.BirthDate).Width(100);
columns.Command(command => { command.Edit().Text(" "); command.Destroy().Text(" "); }).Width(180);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.PopUp))
.Pageable()
.Sortable()
.Scrollable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.StudentID))
.Create(create => create.Action("Students_Create", "Students"))
.Read(read => read.Action("Students_Read", "Students"))
.Update(update => update.Action("Students_Update", "Students"))
.Destroy(destroy => destroy.Action("Students_Destroy", "Students"))
)
)
Controller code
public StudentsController(ApplicationDbContext context)
{
_context = context;
}
// GET: Students
public IActionResult Index()
{
return View();
}
public IActionResult Students_Read([DataSourceRequest] DataSourceRequest request)
{
return Json(_context.Student.ToList().Select(student => new StudentsViewModel
{
FirstName = student.FirstName,
LastName = student.LastName,
BirthDate = student.BirthDate,
}).ToDataSourceResult(request));
}
[AcceptVerbs("Post")]
public ActionResult Students_Create([DataSourceRequest] DataSourceRequest request, StudentsViewModel student)
{
if (student != null && ModelState.IsValid)
{
var entity = new Student();
entity.FirstName = student.FirstName;
entity.LastName = student.LastName;
entity.BirthDate = student.BirthDate;
_context.Student.Add(entity);
_context.SaveChanges();
student.StudentID = (int)entity.StudentID;
}
return Json(new[] { student }.ToDataSourceResult(request, ModelState));
}
[AcceptVerbs("Post")]
public ActionResult Students_Update([DataSourceRequest] DataSourceRequest request, StudentsViewModel student)
{
if (student != null && ModelState.IsValid)
{
var entity = new Student();
entity.StudentID = student.StudentID;
entity.FirstName = student.FirstName;
entity.LastName = student.LastName;
entity.BirthDate = student.BirthDate;
_context.Student.Attach(entity);
_context.Entry(entity).State = EntityState.Modified;
_context.SaveChanges();
}
return Json(new[] { student }.ToDataSourceResult(request, ModelState));
}
[AcceptVerbs("Post")]
public ActionResult Students_Destroy([DataSourceRequest] DataSourceRequest request, StudentsViewModel student)
{
if (student != null)
{
var entity = new Student();
entity.StudentID = student.StudentID;
_context.Student.Attach(entity);
_context.Student.Remove(entity);
_context.SaveChanges();
}
return Json(new[] { student }.ToDataSourceResult(request, ModelState));
}
In debug mode any delete or update actions in grid only triggers Students_Create procedure 10 time. Delete or update never called.

Populating a Kendo Grid when searching

I need to populate Kendo grid from search button. I write personal ID and I should get other information in the grid, but after writing the ID in the textbox and clicking search, I get
"Server was unable to process request. ---> Procedure or function
'PROS_CRA_PUBLIC_GET_DOCUMENT_LIST_BY_PN' expects parameter '#PN',
which was not supplied."
Controller
public ActionResult Search(string personalID, [DataSourceRequest]DataSourceRequest request)
{
var serviceclient = new PersonalInfoServiceClient();
DataSourceResult result = null;
try
{
var items = serviceclient.GetRegistryInfoForPerson(personalID);
result = items.ToDataSourceResult(request);
}
catch
{
throw;
}
finally
{
serviceclient.Close();
}
return Json(result, JsonRequestBehavior.AllowGet);
}
View (part of it)
<div id ="search">
#using (Html.BeginForm("Search", "Main")){
<p> personal number: <input type="text" name="Searchtext" id="SearchString" /> <input type="submit" value="search" name="btnSearch" id="btnSearch" /></p>
}
<div id="civil">
#(Html.Kendo().Grid<PersonalIDCheckerMvCKendo.Models.PersInfo>()
.Name("Grid")
.AutoBind(false)
.Columns(columns =>
{
//columns// })
.Groupable()
.Sortable()
.Scrollable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(c=> c.personalID))
.Read(read => read.Action("Search", "Main").Data("test"))
)
)
</div>
<script>
$("#btnSearch").on('click', function test() {
console.log("click");
var searchText = $("#SearchString").val();
if (searchText == "") {
alert("You must enter a search value");
return;
}
$.ajax({
url: '#Url.Action("Search","Main")',
data: { personalID: searchText},
type: 'POST',
dataType: "json",
success: function(result) {
var grid = $('#Grid').getKendoGrid();
grid.dataSource.data(result);
grid.refresh();
}
});
});
</script>
Model
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ServiceModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using DataAnnotationsExtensions;
namespace PersonalIDCheckerMvCKendo.Models
{
[DataContract(IsReference=true)]
public class PersInfo
{
[DataMember]
[DisplayName("Personal#")]
public string personalID
{
get
{
return _PersonalID;
}
set
{
if (_PersonalID != value)
{
_PersonalID = value;
}
}
}
private string _PersonalID;
[DataMember]
[DisplayName("Name")]
public string FirstName
{
get
{
return _FirstName;
}
set
{
if (_FirstName != value)
{
_FirstName = value;
}
}
}
private string _FirstName;
[DataMember]
[DisplayName("Lastname")]
public string LastName
{
get
{
return _LastName;
}
set
{
if (_LastName != value)
{
_LastName = value;
}
}
}
private string _LastName;
//etc
thanks
You are not passing the personalID.
Add a javascript function that will be responsible for passing the data needed by the controller function, for example
function additionalData() {
return {
personalID: '#Model.personalID'
};
}
then change the DataSource of your grid to make use of the javascript function
.DataSource(dataSource => dataSource.Ajax().ServerOperation(false)
.Read(read => read.Action("Search", "Main")
.Data("additionalData"))
)
also make sure that the
[DataSourceRequest]DataSourceRequest request
parameter is placed first in your controller function, for example
public ActionResult Search([DataSourceRequest]DataSourceRequest request
, string personalID)
also make sure that you are binding the columns of the grid with the properties of the object returned (In your case PersonalIDCheckerMvCKendo.Models.PersInfo). For example
.Columns(columns =>
{
columns.Bound(pi => pi.Name);
columns.Bound(pi => pi.Surname);
// Some other columns.
})
*Update
To assist you I added one of my working grid examples. Here is my grid
#(Html.Kendo().Grid<ClientSearchResult>()
.Name("Grid")
.HtmlAttributes(new {style = "height:400px; cursor:pointer"})
.DataSource(dataSource => dataSource.Ajax().ServerOperation(false)
.Read(read => read.Action("RefreshGrid", "Client")
.Data("additionalData"))
.PageSize(20)
)
.Columns(columns =>
{
columns.Bound(c => c.ClientId);
columns.Bound(c => c.Name);
columns.Bound(c => c.PolicyNumber);
columns.Bound(c => c.ClaimNumber);
columns.Bound(c => c.Status);
columns.Bound(c => c.IsCompany);
})
.Pageable(page => page.Enabled(true).PageSizes(new[] {10, 20, 30, 40}))
.Sortable(sorting => sorting.SortMode(GridSortMode.SingleColumn))
.Scrollable()
.Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
.Events(events => events.Change("grid_selected"))
)
My javascript function
function additionalData() {
return {
cellNumber: '#Model.CellNumber',
name: '#Model.Name',
policyNumber: '#Model.PolicyNumber',
claimNumber: '#Model.ClaimNumber',
brokerCode: '#Model.BrokerCode',
brokerName: '#Model.BrokerName'
};
}
and my controller function
public ActionResult RefreshGrid([DataSourceRequest] DataSourceRequest request
, string cellNumber, string name
, string policyNumber, string claimNumber
, string brokerCode, string brokerName)
{
if (cellNumber == string.Empty && name == string.Empty && policyNumber ==
string.Empty && claimNumber == string.Empty && brokerCode == string.Empty &&
brokerName == string.Empty)
return Json(new List<ClientSearchResult>());
else
{
List<ClientSearchResult> searchResult =
ClientMaintenance.ClientSearch(cellNumber, name, policyNumber, claimNumber,
brokerCode, brokerName).ToList();
var result = searchResult.ToDataSourceResult(request);
return Json(result);
}
}
I fixed it
changed the controller to this:
public ActionResult Search([DataSourceRequest]DataSourceRequest request, string searchString)
{
var serviceclient = new PersonalInfoServiceClient();
DataSourceResult result = null;
if (!String.IsNullOrEmpty(searchString))
{
try
{
var items = serviceclient.GetRegistryInfoForPerson(searchString);
result = items.ToDataSourceResult(request);
}
catch
{
throw;
}
finally
{
serviceclient.Close();
}
}
return Json(result, JsonRequestBehavior.AllowGet);
}
View :
Textbox:
#Html.TextBox("SearchString")
Function:
<script type="text/javascript">
$(document).ready(function(){
$("#btnSearch").click(function (e) {
$.ajax({
url: '#Url.Action("Search","Main")',
type: 'POST',
dataType: "json",
success: function (result) {
$("#Grid").data("kendoGrid").dataSource.read();
$("#Grid").data("kendoGrid").refresh();
e.preventDefault();
}

Kendo Grid: Foreign Key Dropdown does not update grid cell after update

I have a Kendo MVC grid that contains a nullable property (short) that is bound as a foreign key and uses a dropdown list as an editor template. I am also using inline editing.
When the property value is null, the dropdown list selected value does not get set into the grid cell after the update button is clicked. This works fine if incell editing is used. I am looking for a workaround that will solve my problem. I am including a stripped down version of my code below
Everything works if the nullable value is set to a non-null value.
GRID
#(Html.Kendo().Grid<AssetViewModel>()
.Name("DealAssets")
.Columns(c =>
{
c.Bound(x => x.Name);
c.ForeignKey(x => x.AssetTypeID, (IEnumerable<SelectListItem>)ViewBag.AssetTypeList, "Value", "Text");
c.ForeignKey(x => x.SeniorityTypeID, seniorityTypeList, "Value", "Text").EditorTemplateName("GridNullableForeignKey");
c.ForeignKey(x => x.RateBaseID, rateBaseList, "Value", "Text").EditorTemplateName("GridNullableForeignKey"); ;
c.Command(m => { m.Edit(); m.Destroy(); });
})
.ToolBar(toolbar => toolbar.Create().Text("Add New Asset"))
.Editable(x => x.Mode(GridEditMode.InLine))
.DataSource(ds => ds
.Ajax()
.Model(model => model.Id(request => request.ID))
.Read(read => read.Action("ReadAssets", "Deal", new { id = Model.ID }))
.Create(create => create.Action("CreateAsset", "Deal", new { currentDealID = Model.ID }))
.Update(update => update.Action("UpdateAsset", "Deal"))
.Destroy(destroy => destroy.Action("DeleteAsset", "Deal"))
)
)
EDITOR TEMPLATE
#model short?
#{
var controlName = ViewData.TemplateInfo.GetFullHtmlFieldName("");
}
#(
Html.Kendo().DropDownListFor(m => m)
.Name(controlName)
.OptionLabel("- Please select -")
.BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
)
UPDATE ACTION
public ActionResult UpdateAsset([DataSourceRequest] DataSourceRequest request, int ID)
{
var dealAsset = DataContext.DealAssets.SingleOrDefault(o => o.ID == ID);
if (dealAsset != null)
{
if (TryUpdateModel(dealAsset.Asset, new[] {"Name","AssetTypeID","SeniorityTypeID","RateBaseID" }))
{
DataContext.SaveChanges();
}
}
return Json(new[] { new AssetViewModel(dealAsset) }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
}
Telerik just recently added a new HTML attribute, data_value_primitive, to their selectlist that addresses the issue above. The new attribute should be added in the foreign key editor template and set to true.
Html.Kendo().DropDownListFor(m => m)
.Name(controlName)
.OptionLabel("- Please select -")
.BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
**.HtmlAttributes(new { data_value_primitive = true})**
This last section is a modification to the update method to account for the grid not passing back null properties when doing the ajax call. I think this has more to do with how the TryUpdateModel method works
...
if (TryUpdateModel(dealAsset.Asset, new[] {"Name","AssetTypeID","SeniorityTypeID","RateBaseID" }))
{
// If no property passed back then set it to null
var senorityTypeID = ValueProvider.GetValue("SeniorityTypeID");
if (senorityTypeID == null)
{
dealAsset.Asset.SeniorityTypeID = null;
} else {
dealAsset.Asset.SeniorityTypeID = (short)senorityTypeID.ConvertTo(typeof(short));
}
var rateBaseID = ValueProvider.GetValue("RateBaseID");
if (rateBaseID == null)
{
dealAsset.Asset.RateBaseID = null;
} else {
dealAsset.Asset.RateBaseID = (byte)rateBaseID.ConvertTo(typeof(byte));
}
DataContext.SaveChanges();
}
'''

KendoUI Grid Ajax Binding Parameters For Select

I have a basic KendoUI Grid for my ASP.NET MVC app which uses ajax binding for the read. I'd like to enhance this so that a Form above the grid is used to help select data that should be displayed in the grid. This is a standard search form with basic fields like First Name, Last Name, Date of Birth, Customer Source, etc. with a search button. When the search button is pressed, I want to force the grid to go get the data that meets the criteria from the controller by passing in the Search Model with the fields I referenced above.
The search form is contained within the _CustomerSearch partial view.
I've implemented this sort of thing before with the Telerik MVC extensions by tapping into the OnDataBinding client event and updating the parameter values there and then manually making the Ajax call to get the data. It doesn't appear KendoUI will operate this same way.
View
#Html.Partial("_CustomerSearch", Model)
<hr>
#(Html.Kendo().Grid<ViewModels.CustomerModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.Id).Hidden(true);
columns.Bound(p => p.FirstName);
columns.Bound(p => p.LastName);
columns.Bound(p => p.DateOfBirth).Format("{0:MM/dd/yyyy}");
columns.Bound(p => p.IsActive);
})
.Scrollable()
.Filterable()
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("_Search", "Customer"))
)
)
Controller
public ActionResult _Search([DataSourceRequest]DataSourceRequest request)
{
return Json(DataService.GetCustomers2().ToDataSourceResult(request));
}
I envision the controller looking something like this, but can't find any examples of anything being implemented this way, which is what I need help with.
public ActionResult _Search([DataSourceRequest]DataSourceRequest request, CustomerSearchModel customerSearchModel)
{
return Json(DataService.GetCustomers2(customerSearchModel)
.ToDataSourceResult(request));
}
Nicholas answer could work if your requirements can be solved with the built in filtering. But if your requirements can be solved with the built filtering why do you want to create a custom search form?
So I suppose you have a reason to do the search manually so here is how we've done it in our project (so maybe there is more easier way but still this worked for us):
The controller action is fine:
public ActionResult _Search([DataSourceRequest]DataSourceRequest request,
CustomerSearchModel customerSearchModel)
{
return Json(DataService.GetCustomers2(customerSearchModel)
.ToDataSourceResult(request));
}
Next step: you need a JavaScript function which collects the data from the search form (the property names of the JS object should match the property names of your CustomerSearchModel) :
function getAdditionalData() {
// Reserved property names
// used by DataSourceRequest: sort, page, pageSize, group, filter
return {
FirstName: $("#FirstName").val(),
LastName: $("#LastName").val(),
//...
};
}
Then you can configure this function to be called on each read:
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("_Search", "Customer")
.Data("getAdditionalData"))
)
Finally in your button click you just need to refresh the grid with:
$('#Grid').data('kendoGrid').dataSource.fetch();
You can set the filters on the grid by calling filter on the grid's data source.
So in your button's onclick handler function, put something like this:
var $Grid = $('#Grid').data('kendoGrid');
$Grid.dataSource.filter([
{ field: 'FirstName', operator: 'eq', value: $('#firstName').val() },
{ field: 'LastName', operator: 'eq', value: $('#lastName').val() }
]);
Here's a link to the Kendo docs: DataSource.filter
Refer Pass Additional Data to the Action Method
To pass additional parameters to the action use the Data method. Provide the name of a JavaScript function which will return a JavaScript object with the additional data:
A working Search example listed below:
Important: type="button" for the button; And AutoBind(false) for Grid; otherwise, it won’t work
VIEW
#model IEnumerable<KendoUIMvcSample.Models.Sample>
#{
ViewBag.Title = "Index";
}
<script type="text/javascript">
function getAdditionalData()
{
return {
FirstName: 'A',
LastName: 'B',
};
}
$(document).ready(function ()
{
$('#Submit1').click(function ()
{
alert('Button Clicked');
//Refresh the grid
$('#ssgrid222').data('kendoGrid').dataSource.fetch();
});
});
</script>
<h2>Index</h2>
#using (Html.BeginForm())
{
#(Html.Kendo().Grid<KendoUIMvcSample.Models.Sample>()
.Name("ssgrid222")
.Columns(columns => {
columns.Bound(p => p.SampleDescription).Filterable(false).Width(100);
columns.Bound(p => p.SampleCode).Filterable(false).Width(100);
columns.Bound(p => p.SampleItems).Filterable(false).Width(100);
})
.AutoBind(false)
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Orders_Read", "Sample")
.Data("getAdditionalData"))
)
)
<input id="Submit1" type="button" value="SubmitValue" />
}
Controller
namespace KendoUIMvcSample.Controllers
{
public class SampleController : Controller
{
public ActionResult Index()
{
SampleModel AddSample = new SampleModel();
Sample s1 = new Sample();
return View(GetSamples());
}
public static IEnumerable<Sample> GetSamples()
{
List<Sample> sampleAdd = new List<Sample>();
Sample s12 = new Sample();
s12.SampleCode = "123se";
s12.SampleDescription = "GOOD";
s12.SampleItems = "newone";
Sample s2 = new Sample();
s2.SampleCode = "234se";
s2.SampleDescription = "Average";
s2.SampleItems = "oldone";
sampleAdd.Add(s12);
sampleAdd.Add(s2);
return sampleAdd;
}
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request, CustomerSearchModel customerSearchModel)
{
string firstParam = customerSearchModel.FirstName;
return Json(GetOrders().ToDataSourceResult(request));
}
private static IEnumerable<Sample> GetOrders()
{
return GetSamples();
}
}
public class CustomerSearchModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Model
namespace KendoUIMvcSample.Models
{
public class SampleModel
{
public List<Sample> samples;
}
public class Sample
{
public string SampleDescription { get; set; }
public string SampleCode { get; set; }
public string SampleItems { get; set; }
}
}

Resources