Rebind Kendo Grid in MVC - kendo-ui

I am trying to rebind Kendo Grid on a button click after filtering data using the JavaScript below, but it is not working. What should I do?
My HTML code using Kendo.Mvc.Dll:
Html.Kendo().Grid<EquityStreet.Data.ESData.Proc_GetESManagersListAndFilterResult>().Name("GridESManager").BindTo(Model.ESManagersList).Columns(columns =>
{
columns.Bound(m => m.pkESManagerId).Template(#<input type="checkbox" id="#item.pkESManagerId" />).Title("").Width("2%");
columns.Bound(m => m.pkESManagerId).Template(#<text> #item.FirstName #item.LastName</text>).Title("Name");
columns.Bound(m => m.CompanyName).Title("Company");
columns.Bound(m => m.MobileNo).Title("Phone Number");
columns.Bound(m => m.ESManagerStatus).Template(#<text>#(item.ESManagerStatus == 1 ? "Active" : "Inactive")</text>).Title("Status");
columns.Bound(m => m.pkESManagerId).Template(#<text> <a href="../Utilities/NewESManager?EId=#item.pkESManagerId" class="access_btn">
</a><a href="../Utilities/NewESManager?EId=#item.pkESManagerId" class="edit_btn">
</a>
</text>).Title("Actions");
}).ToolBar(tb =>
{
tb.Template("<div class='GridSearchHeader'><div style='float:left'><input type='button' value='Reset Pwd'><input type='button' value='Delete'></div><label>Filter: </label><input type='search' style='width: 230px' id='txtSearch'><select id='Status'><option value=-1>Select</option><option value=1>Active</option><option value=0>Inactive</option></select><input type='button' onclick='FilterList()' value='Go'><input type='button' value='Reset'></div>");
}).Pageable()
)
JavaScript:
$.post('#Url.Action("FilterESManagerList", "../../Utilities")', { Keyword: Search, UserStatus: status }, function (result) {
var grid = $("#GridESManager").data("kendoGrid");
grid.dataSource.data(result);
grid.refresh();
alert(grid);
});

Calling grid.dataSource.data(result) should rebind the grid unless the result is not in the expected format.

It looks that when using ajax-binding, calling grid.dataSource.fetch() will trigger the read method defined in the datasource and rebind automatically.

try this:
$("#gridName").data("kendoGrid").dataSource.sync();

Related

Kendo GRID AddRow by javascript

I want to add row to kendo Grid with inline edit support. I need to do it after grid is initialized and data are loaded.
I tried this:
$(document).ready(function () {
gridAdd(); // no work
});
function gridAdd(){
$(".k-grid-add").click()
}
When I call gridAdd() in DataBound event in Grid, grid freeze and data do not load. What is correct event to perform this function ?
Grid code is before code for gridAdd function:
#(Html.Kendo().Grid<TT.Web.Models.ViewModel.WorkViewModel>()
.Name("gridAdd")
.Events(events => events.Edit("gridEdit").DataBound("databoundinitAdd").Save("gridAddSaveChanges"))
.Columns(columns =>
{
columns.Template(x => x.Id)
.HeaderTemplate("<input id='mastercheckbox' type='checkbox'/>")
.ClientTemplate("#if(Status == 0 || Status == 3) {# <input type='checkbox' name='checkedRecords' value='#= Id #' class='checkboxGroups'/> #} #")
.Width(30)
.HtmlAttributes(new { style = "text-align:center" })
.HeaderHtmlAttributes(new { style = "text-align:center" });
columns.Template(#<text></text>).Title("Status").ClientTemplate("#if(Status == 0) {# <i class='fa fa-bolt icc'></i> #}#" + "#if(Status == 1) {# <i class='fa fa-paper-plane icc'></i> #}#" + "#if(Status == 2) {# <i class='fa fa-check-square-o icc'></i> #}#" + "#if(Status == 3) {# <a class='popoverEl' data-toggle='popover' data-trigger='hover' tabindex='0' title='Důvod zamítnutí' data-content='#=RejectionReason#' ><i class='fa fa-ban icc popoverEl' ></i></a> #}#").HtmlAttributes(new { #class = "icc" });
columns.Bound(work => work.Date).EditorTemplateName("WorkDate").Title(#L("Date"));
columns.Bound(work => work.Project).ClientTemplate("#=Project.Name#").Width(250).Title(#L("ProjectNameP")); // .ClientTemplate("#=Project.Name#")
columns.Bound(work => work.Spp).ClientTemplate("#=Spp.Code#").Width(100);
columns.Bound(work => work.Operation).ClientTemplate("#=Operation.Code#").Width(100).Title(#L("TypeOfOperation"));
columns.Bound(work => work.Hours).Title(#L("Hours"));
//columns.Command(command => { command.Edit(); command.Destroy(); }).Width(172);
columns.Template(#<text></text>).ClientTemplate(
"<div class='btn-group'>" +
"#if(Status == 0 || Status == 3 ) {# <a class='btn btn-success btn-sm k-button-icontext k-grid-edit'><i class='fa fa-pencil'></i></a>#}#" +
"#if(Status == 0 || Status == 3 ) {# <a class='btn btn-sm btn-primary sendToApprove' data-href='" + Url.Action("WorkToApprove", "Home") + "/#=Id#'><i class='fa fa-paper-plane'></i></a>#}#"
+ "#if(Status == 0 ) {# <a data-href='" + Url.Action("WorkDelete", "Home") + "/#=Id#' class='btn btn-sm btn-danger delete-work-item' ><i class='fa fa-times'></i></a>#}#"
+ "</div>"
).Width(130);
})
.ToolBar(toolbar =>
{
toolbar.Create().Text(#L("AddRecord"));
//toolbar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(false)
.Events(events => events.RequestEnd("OnRequestEnd_TopLinePriceGrid"))
.PageSize(20)
//.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.Operation).DefaultValue(ViewData["defaultOperation"] as TT.Web.Models.ViewModel.OperationViewModel);
model.Field(p => p.Spp).DefaultValue(ViewData["defaultSpp"] as TT.Web.Models.ViewModel.SppViewModel);
model.Field(p => p.Project).DefaultValue(ViewData["defaultProject"] as TT.Web.Models.ViewModel.ProjectViewModel);
})
.Read(read => read.Action("WorkRead", "Home").Data("currentWeekInfo")) // Přidádo HTTP parametr s vybranným týdnem
.Create(update => update.Action("EditingInline_Create", "Home").Data("currentWeekInfo"))
.Update(update => update.Action("EditingInline_Update", "Home").Data("currentWeekInfo"))
.Destroy(update => update.Action("EditingInline_Destroy", "Home").Data("currentWeekInfo"))
)
.Pageable() // Enable paging
.Sortable() // Enable sorting
)
Thanks!
EDIT NOT SOLVED BY: in databound Event, but there is a problem. GridAdd cause databound event, so it is calling repeatedly and brower freeze.
setTimeout(function(){
$(".k-grid-add").click()
})
Basically the best way is to get the Grid client side object and then use the client-side API to add the row. Please check the related docuemntation below:
Grid: Server side wrappers fundamentals
Grid: getting the client-side object
Grid: client side API, addRow

Radio Button doesn't reflect Model's value

I have a kendo Grid for a class, and for that class I've built an editor template to produce a radio button for one of the fields.
This radio button doesn't reflect propertie's value and is always false, although I've checked the value, by printing it on the form, and I'm sure it's true. If I set a default value for that field, the radio button will reflect that value, regardless of the real value of the field.
I should note that I'm using a client template to display a text for that field, and it works fine.
This is the Grid:
#(Html.Kendo().Grid<Class>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(x => x.BActive).ClientTemplate("#= BActive ? 'Open':'Close' #");
/// removed for brevity
})
.Editable(editable => editable.Mode(GridEditMode.PopUp))
.DataSource(ds => ds.Ajax()
.Model(model => {
model.Id(x => x.SWhCode);
model.Field(x => x.BActive).DefaultValue(true);
})
)
)
And this is the lines that produce the radio button inside the editorTemplate:
<label>
#Html.RadioButtonFor(x => x.BActive, true, new { #class = "radio-inline" }) Open
</label>
<label>
#Html.RadioButtonFor(x => x.BActive, false, new { #class = "radio-inline" }) Close
</label>
bool type will be render in client like this
true => True
false => False
Have you try to inspect your element rendered in HTML? You'll see that the bool value transform into capitalize string. To overcome this you should change true and false in radio button with type string too.
Your view code should be like this
<label>
#Html.RadioButtonFor(x => x.BActive, "true", new { #class = "radio-inline" }) Open
</label>
<label>
#Html.RadioButtonFor(x => x.BActive, "false", new { #class = "radio-inline" }) Close
</label>

CheckBox and id value to actionresult in kendo ui with ajax binding

I am developing a MVC with kendo UI grid. In which I have grid and one Button. Grid contains check-box. When We click on button check box value(true/false) and Record id should go to action result.
using (Html.BeginForm("Update", "Model"))
{
Html.Kendo().Grid(Model.Users)
.Name("grid")
.Columns(columns =>
{
columns.Bound(o => o.UserName).Width("300px");
columns.Bound(o => o.IsLicensed).Template(o =>
{%><%: Html.CheckBox("license",o.IsLicensed)%> <%: Html.Hidden("id", o.UserId) %><%}).Width("200px");
})
.Resizable(resize => resize.Columns(true))
.Sortable(sorting => sorting.Enabled(true))
.Filterable(f => f.Enabled(true))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(new int[] {10, 20, 50, 100})
.ButtonCount(5))
.Render();
%>
<p>
<input class="k-primary k-button" type="submit" value="Save" name="selectedValues"/>
</p>
<%
Html.EndForm();
}
%>
</div>
<% });
And my actionresult looks as below
public ActionResult Update(string[] license, string[] id)
Now here I am using ajax binding and giving datasource. So I can't use Template. We need to use ClientTemplate. ClientTemplate code changes are shown as below.
.Columns(columns =>
{
columns.Bound(o => o.UserName).Width("300px");
columns.Bound(o => o.IsLicensed).Width("300px").ClientTemplate("<input type='checkbox' name='license' ${ IsLicensed == true ? checked='checked' : ''} enabled />" + "<input type='hidden' name='id' value='#= UserId#' />");
})
.DataSource(datasource => datasource.Ajax().Read(read => read.Action("Customers_Read", "UsersLicensing")).PageSize(10))
.Render();
In previous case when Update actionresult is called both parameter are array of 10 as pagesize is 10 and I can update database. But in this case(with ajax and clientTemplate) id parameter is coming as array of 10 items but license parameter depends on number of checkbox selected(if 3 checkbox is selected then license contains 3 element). So I can't make one to one mapping.
Can anybody help me with this or suggest any better idea?
Try this....Worked for me
columns.Template(#<text></text>).
ClientTemplate("<input type='checkbox' class='chkbx' onclick='chkRoleChkBox(this)'
value='#=RoleId#' # if (DefaultRoleflag == 'Y') { # disabled='disabled' # } #/>").Width(30);
You should be able to change your client template as such:
.ClientTemplate("<input type='checkbox' name='license' ${ IsLicensed == true ? checked='checked' : ''} enabled value='#= UserId#' />")
Put the UserId directly into the value of the checkbox. Then when you post, instead of getting an array of "true" you should get an array of the value (which is the UserId) for the checked items.
Update
If you want to be able to get both the checked and unchecked lists, then you can add the hidden field back to the ClientTemplate.
.ClientTemplate(
"<input type='checkbox' name='license' ${ IsLicensed == true ? checked='checked' : ''} enabled value='#= UserId#' />" +
"<input type='hidden' name='id' value='#= UserId#' />"
)
Then when you post you will have an array of all of the IDs in string[] id and an array of the checked IDs in string[] license. Then to get the unchecked, you can use use System.Linq namespace and use Enumerable.Except.
public ActionResult Update(string[] license, string[] id)
{
//....
var unchecked = id.Except(license).ToArray();
//...
}

How to get row value from grid when toolbar is clicked in kendo ui mvc grid

How to get row value from grid when toolbar is clicked in kendo ui mvc grid.
sample View code:
<div id="kendoGrid">
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Template(#<input id='chkPayment' type='checkbox' class='check-box' />).Title("Select");
columns.Bound(m => m.PaymentDetailDto.InvoiceNumber);
columns.Bound(m => m.PaymentDetailDto.ModifiedDate).Title("Invoice Date");
})
.ToolBar(x => x.Custom().Text("Make Payment").HtmlAttributes(new { id = "btnMakePayment" }))
)
</div>
Sweeps the grid and search for the value it
$('input[type="checkbox"]').each(function () {
var chkPayment = $(this);
});

Adding New Row Restriction in Kendo Grid MVC

I have a Kendo grid and a Save button on top of the page. When I click on “Add New Record” toolbar, a new row is added in the grid (client side). When I click on save button, I get the updated viewmodel in my controller’s action method which in turns add/update data in the database.
Now, I want to restrict adding a row in the grid if the grid has already 5 rows in it which means user will not be able to add a new row if the grid reaches its limit (which is 5 rows).
Can anyone of you please give me a sample client side script(jquery) that will restrict user to add new row in the grid?
Thank you very much!!!!!!!
Index.cshtml
#using (Html.BeginForm("Save", "UDF", FormMethod.Post))
{
<input class="button" type="submit" name="save" value="Save"/>
#(Html.Kendo().Grid(Model.List1)
.Name("List1")
.HtmlAttributes(new { style = "width:auto;height:100%" })
.ToolBar(toolbar => toolbar.Create().Text("Add New Record"))
.Editable(editable => editable.Mode(GridEditMode.InCell).CreateAt(GridInsertRowPosition.Top))
.Columns(columns =>
{
columns.Bound(p => p.Title)
.ClientTemplate("#= Title #" +
"<input type='hidden' name='DateFields[#= index(data)#].Title' value='#= Title #' />")
.Title("Title").HtmlAttributes(new { style = "width:30%" });
columns.Bound(p => p.MaxPrecision).Title("Decimal Places")
.ClientTemplate("#= MaxPrecision #" +
"<input type='hidden' name='DateFields[#= index(data)#].MaxPrecision' value='#= MaxPrecision #' />");
columns.Bound(p => p.IsObsolete).Title("Obsolete")
.ClientTemplate("#= IsObsolete #" +
"<input type='hidden' name='DateFields[#= index(data)#].IsObsolete' value='#= IsObsolete #' />");
})
.DataSource(datasource => datasource
.Ajax()
.Model(model =>
{
{
model.Id(p => p.Title);
model.Field(p => p.Title).Editable(true);
model.Field(p => p.MaxPrecision).Editable(true);
model.Field(p => p.IsObsolete).Editable(true);
}
}
)
)
)
}
You can use the toolbar template, like the one demonstrated here.
The template can look something like this:
<button class="k-button" id="myAdd">My Custom Add</button>
Once the Grid is initialized you can attach click handler which adds the new row based on your condition.
$('#myAdd).click(function(){
var gr = $('#gridName').data('kendoGrid');
if(gr.dataSource.data().length<5){
gr.addRow();
}
})
The methods used above are all covered in the documentaion.

Resources