Passing data from Kendo window selected rows to parent grid - model-view-controller

I am trying to pass data back from a Kendo window to the parent page but its not working. Here is my code. Any help would be appreciated
Any help resolving this would be appreciated. Everything works except the grid on the parent page is not getting populated. Javascript is crashing when it tries to populate the parent pages grid.
<h5 class="bold"><a name="associates"></a>Known Associates</h5>
<div id="GridMessage_Associate" style="display: none;"></div>
#(Html.Kendo().Grid<PeopleSearchResultDO>()
.Name("AssociateGrid")
.AutoBind(false)
.HtmlAttributes(new { style = "display:none;" })
.Columns(columns =>
{
columns.Bound(p => p.PersonId).ClientTemplate("#= PersonId #" + "<input type='hidden' name='PersonAssociates[#= indexAssociate(data) #].PersonId' value='#= PersonId #' />");
columns.Bound(p => p.FirstName).ClientTemplate("#= FirstName #" + "<input type='hidden' name='PersonAssociates[#= indexAssociate(data) #].FirstName' value='#= FirstName #' />");
columns.Bound(p => p.MiddleName).ClientTemplate("#= MiddleName #" + "<input type='hidden' name='PersonAssociates[#= indexAssociate(data) #].MiddleName' value='#= MiddleName #' />");
columns.Bound(p => p.LastName).ClientTemplate("#= LastName #" + "<input type='hidden' name='PersonAssociates[#= indexAssociate(data) #].LastName' value='#= LastName #' />");
columns.Bound(p => p.DOB).ClientTemplate("#= DOB #" + "<input type='hidden' name='PersonAssociates[#= indexAssociate(data) #].DOB' value='#= DOB #' />");
columns.Bound(p => p.Age).ClientTemplate("#= Age #" + "<input type='hidden' name='PersonAssociates[#= indexAssociate(data) #].Age' value='#= Age #' />");
columns.Bound(p => p.LastFourOfSSN).ClientTemplate("#= LastFourOfSSN #" + "<input type='hidden' name='PersonAssociates[#= indexAssociate(data) #].LastFourOfSSN' value='#= LastFourOfSSN #' />");
columns.Bound(p => p.AddressLine1).ClientTemplate("#= AddressLine1 #" + "<input type='hidden' name='PersonAssociates[#= indexAssociate(data) #].AddressLine1' value='#= AddressLine1 #' />");
columns.Bound(p => p.CityOther).ClientTemplate("#= CityOther #" + "<input type='hidden' name='PersonAssociates[#= indexAssociate(data) #].CityOther' value='#= CityOther #' />");
columns.Bound(p => p.GenderShortName).ClientTemplate("#= GenderShortName #" + "<input type='hidden' name='PersonAssociates[#= indexAssociate(data) #].GenderShortName' value='#= GenderShortName #' />");
columns.Bound(p => p.RaceShortName).ClientTemplate("#= RaceShortName #" + "<input type='hidden' name='PersonAssociates[#= indexAssociate(data) #].RaceShortName' value='#= RaceSHortName #' />");
}
)
.DataSource(
dataSource => dataSource
.Ajax()
.ServerOperation(false)
)
)
<br />
<br />
<!-- Modal -->
<input id="openassociates" value="Search for an Associate" class="btn btn-default btn-lg" />
#(Html.Kendo().Window()
.Name("associatewindow")
.Width(1400)
.Height(500)
.Draggable()
.Resizable()
.Title("Add New Person")
.Visible(false)
.Modal(true)
.Actions(actions => actions
.Minimize()
.Maximize()
.Close().Refresh()
)
.Content("loading associates ...")
.LoadContentFrom("LoadAssociatesForm", "Person")
.Events(ev => ev.Close("onClose"))
)
<div class="responsive-message"></div>
<script>
function onClose() {
$("#openassociates").show();
}
$(document).ready(function () {
$("#openassociates").bind("click", function () {
$("#associatewindow").data("kendoWindow").open();
$("#openassociates").hide();
});
});
</script>
<p>
<input type="submit" id="btnPersonSave" value="Save" class="btn btn-lg btn-primary" />
</p>
}
</div>
<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 indexAssociate(dataItem) {
var data = $("#AssociateGrid").data("kendoGrid").dataSource.data();
return data.indexOf(dataItem);
}
**Here is the popup Window content**
<script type="text/javascript">
function getPeopleSearchCriteria() {
var searchInput = {
FirstName: $("#PeopleSearchForm").find("#PeopleSearchInput_FirstName").val(),
MiddleName: $("#PeopleSearchForm").find("#PeopleSearchInput_MiddleName").val(),
LastName: $("#PeopleSearchForm").find("#PeopleSearchInput_LastName").val(),
LegalFullName: $("#PeopleSearchForm").find("#PeopleSearchInput_LegalFullName").val(),
Address1: $("#PeopleSearchForm").find("#PeopleSearchInput_Address1").val(),
Address2: null,
Address3: null,
StateId: $("#PeopleSearchForm").find("#PeopleSearchInput_StateId").val(),
PostalCode: $("#PeopleSearchForm").find("#PeopleSearchInput_PostalCode").val(),
PhoneNumber: $("#PeopleSearchForm").find("#PeopleSearchInput_PhoneNumber").val(),
DateOfBirthStart: $("#PeopleSearchForm").find("#PeopleSearchInput_DateOfBirthStart").val(),
DateOfBirthEnd: $("#PeopleSearchForm").find("#PeopleSearchInput_DateOfBirthEnd").val(),
GenderId: $("#PeopleSearchForm").find("#PeopleSearchInput_GenderId").val(),
EthnicityId: null,
LastFourOfSsn: $("#PeopleSearchForm").find("#PeopleSearchInput_LastFourOfSSN").val(),
RaceId: $("#PeopleSearchForm").find("#PeopleSearchInput_RaceId").val(),
CaseId: $("#PeopleSearchForm").find("#PeopleSearchInput_CaseId").val(),
DocketNumber: $("#PeopleSearchForm").find("#PeopleSearchInput_DocketNumber").val(),
CaseOpenStartDate: $("#PeopleSearchForm").find("#PeopleSearchInput_CaseOpenStartDate").val(),
CaseOpenEndDate: $("#PeopleSearchForm").find("#PeopleSearchInput_CaseOpenEndDate").val(),
CasePersonTypeId: $("#PeopleSearchForm").find("#PeopleSearchInput_CasePersonTypeId").val(),
}
var model = {
PeopleSearchInput: searchInput
}
return model;
}
#(Html.Kendo().Grid<PeopleSearchResultDO>()
.Name("AssociateResultsGrid")
.AutoBind(false)
.HtmlAttributes(new { style = "display:none;" })
.Columns(columns =>
{
columns.Select().Width(50);
columns.Bound(p => p.PersonId).Hidden(true);
columns.Bound(p => p.FirstName).ClientTemplate("<strong>#: FirstName #</strong>");
columns.Bound(p => p.MiddleName).ClientTemplate("<strong>#: MiddleName #</strong>");
columns.Bound(p => p.LastName).ClientTemplate("<strong>#: LastName #</strong>");
columns.Bound(p => p.DOB);
columns.Bound(p => p.Age);
columns.Bound(p => p.LastFourOfSSN);
columns.Bound(p => p.AddressLine1);
columns.Bound(p => p.CityOther);
columns.Bound(p => p.GenderShortName);
columns.Bound(p => p.RaceShortName);
})
//there is a bug with persisting right now. We want to persist the selected rows even after paging or sorting.
//.PersistSelection()
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.Read(read =>
read.Action("AssociatesSearchResults", "Person")
.Data("getPeopleSearchCriteria").Type(HttpVerbs.Post)
)
//we are disabling paging and sorting until the issue with persisitng is resolved
//.PageSize(10)
//.Sortable()
)
.NoRecords(n => n.Template("<div class='alert alert-danger'><h3 class='text-danger bold'>No records returned!</h3></div>"))
//.Scrollable(s => s.Height("auto"))
.Scrollable(s => s.Height("400px"))
//.Pageable(p => p.PageSizes(new int[] { 5, 10, 20, 50, 100 }))
)
<p> <input type="button" id="btnAddAssociate" value="Add Selected Associate(s)" class="btn btn-default bold" style="display: none;" />
</p>
<script type="text/javascript">
$("#btnAddAssociate").click(function () {
$("#GridMessage_Associate").css("display", "none");
var entityGrid = $("#AssociateResultsGrid").data("kendoGrid");
var rows = entityGrid.select();
//finally close modal window
var myxxWindow = $("#associatewindow");
myxxWindow.data("kendoWindow").close();
if (rows !== undefined) {
rows.each(function (index, row) {
var selectedItem = entityGrid.dataItem(row);
// selectedItem has EntityVersionId and the rest of your model
var assogrid = $("#AssociateGrid").data("KendoGrid");
assogrid.dataSource.add(
{
PersonId: selectedItem.PersonId,
FirstName: selectedItem.FirstName,
MiddleName: selectedItem.MiddleName,
LastName: selectedItem.LastName,
DOB: selectedItem.DOB,
Age: selectedItem.Age,
LastFourOfSSN: selectedItem.LastFourOfSSN,
AddressLine1: selectedItem.AddressLine1,
CityOther: selectedItem.CityOther,
GenderShortName: selectedItem.GenderShortName,
RaceShortName: selectedItem.RaceShortName
});
$("#AssociateGrid").css("display", "block");
//clear selected items in parent grid
});
}
else {
$("#AssociateGrid").css("display", "none");
}
})
</script>

The problem was with typos and case-sensitivity. For example, I used .data("KendoGrid") instead of .data("kendoGrid"). I also had a typo in line
var selectedItem = entityAssociateGrid.dataItem(row)
it should have been
var selectedItem = entityAssociateGridDS.dataItem(row)

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

Kendo grid dropdown issue

I have a view with tabs and each tab has a kendo grid with inline edit and have dropdown inside the grid. Problem which i am facing is when i update the value of the drop down is not showing the updated value but when i refresh the page the updated value is showing. But if i refresh the problem here is if i update the value is the sceond tab it i do refresh it will go to second tab. Is there any way I can acheive this without refesh.
#model BHI.TESQ.Entities.Interfaces.Models.ILocationAdminModel
#if (TempData["Result"] == "Data Saved Successfully")
{
<script>
alert('Location Data Saved Successfully');
</script>
}
#using (Html.BeginForm("SaveLocationAdmin", "Administration", FormMethod.Post))
{
<div style="margin-top: 45px;height:400px">
<h5 class="page-header k-block k-primary" style="overflow: hidden; margin-left: 5px; max-width: 1133px;">#ViewBag.Title</h5>
<table style="width: 100%; margin-top: 0px">
<tr style="margin-top: 0px;">
<td>
#*<table style="width: 100%">
<tr>
<td>*#
#(Html.Kendo().Splitter()
.Name("vertical")
.HtmlAttributes(new { style = "min-height:400px" })
.Orientation(SplitterOrientation.Horizontal)
.Panes(verticalPanes =>
{
verticalPanes.Add()
.Size("150px")
.HtmlAttributes(new { style = "min-height:400px" })
.Scrollable(false)
.Resizable(false)
.Content(Html.Action("AdminLinks").ToString());
verticalPanes.Add()
.HtmlAttributes(new { id = "top-pane" })
.Scrollable(false)
.Collapsible(false)
.Content(
Html.Kendo().Splitter()
.Name("horizontal")
.HtmlAttributes(new { style = "min-height:400px" })
.Panes(horizontalPanes =>
{
horizontalPanes.Add()
.HtmlAttributes(new { id = "left-pane" })
.Size("300px")
.Collapsible(true)
.Resizable(false)
.Content(#<div class="pane-content">
<h6 class="header k-block">Create New Location</h6>
<table>
<tr>
<td class="td-style">Location Name<span class="asterisk_input"></span></td>
<td>
<input id="txtLocName" name="txtLocName" type="text" class="textbox" required />
</td>
</tr>
<tr>
<td class="td-style">Country<span class="asterisk_input"></span></td>
<td>
#(Html.Kendo().DropDownList()
.Name("ddCountry")
.HtmlAttributes(new { required = "required" })
//.BindTo(new List<string>() {
// "United States",
// "United Kingdom (UK)",
// })
.BindTo(#Model.Country)
.OptionLabel("--Select Country--")
.DataTextField("CountryName")
.DataValueField("CountryId")
.Events(e => e.Change("OnCountryChange"))
)
<input type="hidden" id="hddCountry" name="hddCountry" value="" />
</td>
</tr>
<tr>
<td class="td-style">State</td>
<td>
#(Html.Kendo().DropDownList()
.Name("ddState")
.OptionLabel("--Select State--")
.DataTextField("StateName")
.DataValueField("StateId")
.Events(e => e.Change("OnStateChange"))
//.BindTo(new List<string>() {
// "Texas",
// })
.DataSource(source =>
{
source.Read(read => { read.Action("GetStateList", "Administration").Data("filterState"); }).ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.CascadeFrom("ddCountry")
)
<script>
function filterState() {
return {
countryId: $("#ddCountry").val()
};
}
</script>
<input type="hidden" id="hddState" name="hddState" value="" />
</td>
</tr>
<tr>
<td class="td-style">Location Status<span class="asterisk_input"></span></td>
<td>
#*#(Html.Kendo().DropDownList()
.Name("ddLocStatus")
.BindTo(new List<string>() {
"Active",
"In-Active",
})
)*#
<input id="chkBoxStatus" type="checkbox" name="chkBoxStatus" value="true" />
</td>
</tr>
<tr>
<td align="right">
#(Html.Kendo().Button()
.Name("btnInsert")
.Events(ev => ev.Click("onClick"))
.HtmlAttributes(new { type = "submit", #class = "btn btn-primary button" })
.Content("Save"))
</td>
<td>
#(Html.Kendo().Button()
.Name("btnCancel")
.HtmlAttributes(new { type = "button", #class = "btn btn-primary button" })
.Content("Cancel"))
</td>
</tr>
</table>
</div>
);
horizontalPanes.Add()
.HtmlAttributes(new { id = "center-pane" })
.Scrollable(false)
.Content(#<div>
#(Html.Kendo().Grid(Model.Locations)
.Name("Grid")
.HtmlAttributes(new { style = "min-height:400px" })
.Columns(columns =>
{
columns.Command(command => { command.Edit().HtmlAttributes(new { type = "button", #class = "btn btn-primary button" }); }).Width(100);
columns.Bound(p => p.LocationId).Width(140).Hidden(true);
columns.Bound(p => p.LocationName).Width(140);
columns.Bound(p => p.CountryId).EditorTemplateName("CountryNames").Title("CountryName").ClientTemplate("#:CountryName#").Width(150);
columns.Bound(p => p.StateId).EditorTemplateName("StateNames").Title("StateName").ClientTemplate("#:StateName#").Width(150);
columns.Bound(p => p.IsActive).Width(100);
})
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Pageable()
.Navigatable()
.Sortable()
.Scrollable()
.Groupable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(false)
.Events(events => { events.Error("error_handler"); events.RequestEnd("onRequestEnd"); })
.Model(model => { model.Id(p => p.LocationId); model.Field(p => p.LocationId).Editable(false); })
.Update(update => update.Action("Update_Location", "Administration"))
)
)
</div>
);
}).ToHtmlString()
);
})
)
</td>
</tr>
</table>
#*</td>
</tr>
</table>
*#
</div>
}
<style scoped>
#vertical {
width: 95%;
}
.pane-content {
width: 300px;
}
div.k-grid-content {
min-height: 300px;
}
</style>
<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);
var grid = $("#Grid").data("kendoGrid");
grid.cancelChanges();
}
}
$(document).ready(function () {
$('#btnCancel').click(function () {
$(':input').not(':button, :submit, :reset, :hidden').val('')
$('input:checkbox').removeAttr('checked')
var dropdownlist = $("#ddCountry").data("kendoDropDownList");
dropdownlist.select(0);
var dropdownlist = $("#ddState").data("kendoDropDownList");
dropdownlist.select(0);
});
});
function onClick(e) {
var locationName = $("#txtLocName").val();
if (locationName != "") {
var selectedText = $("#ddCountry").data("kendoDropDownList").text();
if (selectedText == "--Select Country--") {
alert('Please select country');
}
}
}
function OnCountryChange(e) {
var selectedText = $("#ddCountry").data("kendoDropDownList").text()
$("#hddCountry").val(selectedText);
}
function OnStateChange(e) {
var selectedText = $("#ddState").data("kendoDropDownList").text()
$("#hddState").val(selectedText);
}
function onRequestEnd(e) {
if (e.type == "create" || e.type == "update") {
if (e.response == null || e.response.Errors == null) {
alert("Location Data Updated Successfully");
}
}
}
</script>
Ok. So taking your code sample and assuming a couple of things:
Your code:
public ActionResult Update_Parameter([DataSourceRequest] DataSourceRequest request, Parameter UpdatedParameter)
{
try
{
mTestAdminLogic.SaveModel((ITestAdminModel)model, ViewBag.ApplicationId, Operation.UpdateParameter);
}
catch (Exception ex)
{
ModelState.AddModelError("ParameterUpdateError", ex.Message);
}
return RedirectToAction("TestAdmin");
}
and these are my changes:
public JsonResult Update_Parameter([DataSourceRequest] DataSourceRequest request, Parameter UpdatedParameter)
{
var returnModel = {your return model here};
try
{
returnModel = mTestAdminLogic.SaveModel((ITestAdminModel)model, ViewBag.ApplicationId, Operation.UpdateParameter);
}
catch (Exception ex)
{
ModelState.AddModelError("ParameterUpdateError", ex.Message);
}
return Json(new[] { returnModel }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.DenyGet);
}
So let me explain.
If this action is only being used to update the Grid then change it to a JsonResult as the result of the grid update will be expecting JSON back.
I am assuming you have left our the declaration of your Data Layer logic and have cut it down to this single line:
mTestAdminLogic.SaveModel((ITestAdminModel)model, ViewBag.ApplicationId, Operation.UpdateParameter);
now if this model is different to the one expected by the grid the resulting action of this line should return back the appropriate model that the grid is expecting. As you have not declared that in your grid I am assuming it is some kind of LocationBasedModel.
Now once this update has completed then you should be returning back the appropriate model and adding the following Using statement using Kendo.Mvc.Extensions; this will give you access to the .ToDataSourceResult() extension method which will then allow you to transform this single model back to the grid and let the grid update its view of the data. Including the request and modelstate will also provide any errors and apply any existing filtering etc. back to the grid.
This would resolve the issue with the page "refreshing" itself everytime this action is called.
Any issues let me know and I will update my answer to reflect any changes you need.

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();
//...
}

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.

Telerik MVC Grid - HiddenIndexerInputForModel in ClientTemplate

MVC3 and using the Telerik Grid.
I'm using Phil Haacks Hidden Indexer Input For Model to bring form values back. Only problem is that when using Ajax as the databinder any Templates used need to have a corresponding ClientTemplate. This is where I'm having a problem. How do I insert this, and the iterator into the ClientTemplate, which is expecting a string?
This is what I've tried to no avail ... when I run the page I get an error saying 'Iter' is not defined.
<% int Iter = 0; %>
<% Html.Telerik().Grid(Model.TransferStudents)
.Name("TransferStudents")
.Columns(columns =>
{
columns.Bound(o => o.Name)
.Width(250);
columns.Template(o =>{%>
<%: Html.HiddenFor(model => Model.TransferStudents[Iter].StudentId)%>
<%: Html.CheckBoxFor(model => Model.TransferStudents[Iter].Transfer)%>
<%})
.ClientTemplate("<input type='hidden' id='StudentId' value='<#= StudentId #>' /><input type='checkbox' name='Transfer' <#= Transfer? \"checked='checked'\" :\"\" #> />")
.HtmlAttributes(new { #style = "text-align: center;" })
.HeaderHtmlAttributes(new { #style = "text-align: center;" })
.HeaderTemplate("Check All <input type='checkbox' id='chkAll' />")
.Width(105);
columns.Template(o =>{ %><% Iter = Iter + 1; %><%})
.ClientTemplate("<# Iter = Iter + 1; #>")
.Hidden();
columns.Template(o =>{ %><%: Html.HiddenIndexerInputForModel()%><% })
.ClientTemplate("<#= Html.HiddenIndexerInputForModel() #>")
.Hidden();
})
.DataBinding(dataBinding => dataBinding.Ajax().OperationMode(GridOperationMode.Server).Select("_Transfer", "Administration"))
.Pageable(paging => paging.Style(pagerStyles).PageSize(2, new[] { 5, 10, 15, 25, 50, 200 }).Position(GridPagerPosition.Top).Total((int)ViewData["total"]))
.Sortable()
.NoRecordsTemplate("<p class='instructions'>No Records Available</p>")
.Render();
%>
Any pointers would be appreciated.
The ClientTemplate expects a string which will be translated to JavaScript and executed in the browser (client-side). Any server code such as Html.HiddenIndexerInputForModel() won't work - there is no JavaScript equivalent. You need to use plain html as you have done in the other column.

Resources