I have recently had an issue with Kendo MVC where I have needed to drag a product code from one Kendo Grid into another where the cell value is empty.
Scenario:
Grid A, products ordered, where the vendor sending the list of products doesnt have a full product list and 90% accurate descriptions.
Grid B, Products, with full \ correct descriptions and product codes.
I now need to populate Cell x in Grid A, with data from Cell Y in Grid B. In the current windows (WinForms) application, the user can use drag and drop.
Issue:
Kendo Grids do not easily provide a drag and drop feature.
Kendo themselves, admittedly a while back say this is not supported but produced a fiddle that would allow the dragging and dropping of a cell to re-order the row, and thats about it.
They also, never produced any scenario for ASP.Net MVC.
As this is something that I need, and also appears to be something that others may have searched for, you will see below the code in here to help someone who was \ is in my position, and a fiddle for the Kendo UI, and the MVC examples.
Because of how my project is organised and is using Typescript the MVC version isnt going to be 1:1 exact but will be close enough for someone to follow.
A few caveats on this is when you pick up the item, you can click anywhere on the row. (if anyone can refine this please post an answer, I will test and if it works I will upvote and also incorporate your answer with working code.
In addition to the above the dataItem that you pick up is picked up in a position relative to where the mouse is. This I will fix over time, but if anyone gets to this before me please feel free as above.
First,
Kendo UI Code
Html
<html>
<head>
<title>KendoUI Test Page</title>
<link href="//kendo.cdn.telerik.com/2018.3.1017/styles/kendo.common.min.css" rel="stylesheet" />
<script src="//code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="//kendo.cdn.telerik.com/2018.3.1017/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid"></div>
<div id="grid2"></div>
</body>
</html>
CSS
.hint {
padding: 7px 10px;
background-color: #FFFFFF;
}
**JavaScript \ JQuery **
var data = [
{ id: 1, text: "text 1", position: 0 },
{ id: 2, text: "text 2", position: 1 },
{ id: 3, text: "text 3", position: 2 }
]
var data2 = [
{ id: 4, text: "", position: 0 },
{ id: 5, text: "", position: 1 },
{ id: 6, text: "", position: 2 }
]
var dataSource = new kendo.data.DataSource({
data: data,
schema: {
model: {
id: "id",
fields: {
id: { type: "number" },
text: { type: "string" },
position: { type: "number" }
}
}
}
});
var dataSource2 = new kendo.data.DataSource({
data: data2,
schema: {
model: {
id: "id",
fields: {
id: { type: "number" },
text: { type: "string" },
position: { type: "number" }
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
scrollable: false,
columns: ["id", "text"]
}).data("kendoGrid");
var grid2 = $("#grid2").kendoGrid({
dataSource: dataSource2,
scrollable: false,
columns: ["id", "text"]
}).data("kendoGrid");
grid.table.kendoDraggable({
filter: "tbody > tr",
group: "gridGroup",
threshold: 100,
hint: function(e) {
var dataItem = grid.dataItem(e);
return $('<div class="hint">' + dataItem.text + '</div>').css({ marginLeft: e.clientX, marginTop: e.clientY });
}
});
grid2.table.kendoDropTarget({
group: "gridGroup",
drop: function(e) {
e.draggable.hint.hide();
var dest = $(document.elementFromPoint(e.clientX, e.clientY));
var row = dest.closest('tr')
var uid = row[0].dataset.uid
var originalVal = dest[0].innerHTML
var target = dataSource2.getByUid(uid)
var g = $("#grid2").data("kendoGrid")
$.each(g.dataSource.data(), function(idx, gridrow){
if(gridrow.uid === uid){
var dataItem = g.dataSource.get(gridrow.id)
dataItem.set("text", e.draggable.hint[0].innerHTML);
}
})
}
});
Fiddle
https://jsfiddle.net/SimonPrice/t2aju3c6/77/
MVC 5
Razor Partial
<div class="row">
<div id="divOrderedLines" class="col-md-6 col-sm-6 col-xs-6" hidden>
<div class="panel panel-default">
<div class="panel-heading">OrderedLines</div>
<div class="panel-body">
#Html.Partial("_orderedLines")
</div>
</div>
</div>
<div id="divProductLines" class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">Product Lines</div>
<div class="panel-body">
#Html.Partial("_productLines")
</div>
</div>
</div>
</div>
Ordered Lines \ Dropping \ Droppable Grid
#(Html.Kendo().Grid<zzzViewModel>
()
.Name("epsGrid")
.Columns(columns =>
{
//Columns removed
columns.Bound(c => c.ProductCode).HtmlAttributes(new { #class = "drop-target" });
})
.Events(evt => evt.DataBound("fe_rxManager.SetEpsTableOptions"))
.Events(evt => evt.Change("fe_rxManager.styleColumn"))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5)
)
.ToolBar(toolbar =>
{
toolbar.Template(#<text><button id="btnNewOrder" class="btn btn-default" disabled="disabled">New Order <i class="fa fa-plus"></i></button></text>);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Ordered_Read", "RxManager"))
.PageSize(20)
)
)
Product Lines \ Draggable Grid
#(Html.Kendo().Grid<xxxViewModel>
()
.Name("rxGrid")
.Columns(columns =>
{
columns.Bound(c => c.OrderId).Visible(false);
columns.Bound(c => c.LineID).Visible(false);
columns.Bound(c => c.ProductCode).HtmlAttributes(new { #class= "product-code" });
columns.Bound(c => c.Quantity);
columns.Bound(c => c.CPQuantity);
columns.Bound(c => c.PQuantity);
columns.Bound(c => c.Description);
columns.Bound(c => c.OnHandQuantity);
})
.Events(evt => evt.DataBound("fe_rxManager.rxLinesDataChanged"))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5)
)
.Editable(m => m.Mode(GridEditMode.InCell).DisplayDeleteConfirmation(false))
//.BindTo(#Model.xxxLines)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Product_Read", "RxManager").Data("fe_rxManager.xxxLines_Read_AdditionalData"))
.Model(model =>
{
model.Id(l => l.xxxLineID);
model.Field(p => p.ProductCode).Editable(false);
model.Field(p => p.Description).Editable(false);
model.Field(p => p.Quantity).Editable(false);
model.Field(p => p.CPQuantity).Editable(false);
model.Field(p => p.PQuantity).Editable(true);
model.Field(p => p.PQuantityPrice).Editable(false);
model.Field(p => p.OnHandQuantity).Editable(false);
})
.PageSize(20)
))
Typscript \ JavaScript \ JQuery
SetEpsTableOptions = (e: any) => {
this.dragAndDrop();
this.hideLastColumn(); // Dont worry about this
this.styleColumn(e); // Dont worry about this
}
dragAndDrop = () => {
var rxGrid = $("#rxGrid").data("kendoGrid") as any;
rxGrid.table.kendoDraggable({
filter: "tbody > tr",
group: "gridGroup",
threshold: 100,
hint(e) {
var dataItem = rxGrid.dataItem(e);
return $('<div class="hint">' + dataItem.ProductCode + '</div>').css({ marginLeft: e.clientX, marginTop: e.clientY });
}
});
var epsGrid = $("#epsGrid").data("kendoGrid") as any;
epsGrid.table.kendoDropTarget({
group: "gridGroup",
drop(e) {
e.draggable.hint.hide();
var dest = $(document.elementFromPoint(e.clientX, e.clientY));
var row = dest.closest('tr');
var uid = row[0].dataset.uid;
$.each(epsGrid.dataSource.data(),
(idx, gridrow) => {
if (gridrow.uid === uid) {
var dataItem = epsGrid.dataSource.get(gridrow.id);
dataItem.set("ProductCode", e.draggable.hint[0].innerHTML);
}
});
}
});
}
Hopefully this post can help a few people out. Please feel free to leave positive comments that could either help improve this post.
Related
I created a table in a div only with Json.
The div looks like this:
<div id="datatable" class="datatable" data-mdb-hover="true"
data-mdb-border-color="dark"
data-mdb-full-pagination="true"
data-mdb-clickable-rows="true"
>
</div>
then I create the table:
const columns = [
{label: 'ID', field: 'id'},
{label: 'Role', field: 'role'},
];
const asyncTable = new mdb.Datatable(
document.getElementById('datatable'),
{columns,},
{loading: true}
)
fetch('/api/roles')
.then((response) => response.json())
.then((data) => {
asyncTable.update(
{
rows: data.map((roles) => ({
...roles,
name: `${roles.id}`,
role: `${roles.name}`,
})),
},
{loading: false}
);
});
Now I try to change the class to "active" if I click on a tr like so:
// function to select the row
const table = document.getElementById('datatable');
table.addEventListener('rowClick.mdb.datatable', (e) => {
const selected_item_id = e.row.id
//console.log(e);
//event.target._setClassNames("active");
event.target.querySelector("tbody tr").className += "active"
activeT.push(selected_item_id)
});
It is working but only in the First tr. if I click on the 2nd tr it adds the "active" to the first tr again..
In the browserconsole is this after 2 clicks. Like you can see the double active here:
<tr scope="row" data-mdb-index="0" class="activeactive"><td style="" class="" data-mdb-field="id" false="">18</td><td style="" class="" data-mdb-field="role" false="">Admin</td></tr>
Maybe anyone is able to help me!
Try this
<script>
$('tr').onclick(function (e) {
$(this).toggleClass('active');
})
</script>
So I have this template that utilizes KendoUI to render a grid. Here's a part of it:
<script id="rowTemplateCourse" type="text/x-kendo-tmpl">
<tr data-cid="#: id #" class="course-row" id="course-row#: id #">
<td>
<span class="circle-indicator label-#if(package_is_active == 1){#success#}else{#danger#}#"></span>
</td>
<td>
#: course_name # - #= name#
</td>
<td>
<span class="badge element-bg-color-blue">ver. #:version_number#</span>
</td>
</tr>
</script>
I get the needed information from a php controller, that loads a variable in my view that holds this template. Variable holds this sort of data:
[1] => Array(
[id] => 544
[course_name] => Course for whatever
[price] => 52
[logo] => assets/images/new_course.png
[version_number] => 1
[parent_version_id] => 0
[course_price] => 52.00
[description_for_school] =>
[is_print_only] => 0
[offer_pdf] => 0
[pdf_final_price] => 0.00
[simple_course] => 0
[state_id] => 50
[name] => Tennessee
[cs_days_to_complete] => 120
[course_is_active] => 1
[user_in_course] => no
[user_is_waiting] => no
[days_to_complete] => 0)
In my view, I parse this variable like so:
var course_data = JSON.parse('<?php print(json_encode($courses));?>');
This works correctly and returns the same data like so (copy from console.log):
1: Object
course_is_active:"1"
course_name:"Course for whatever"
course_price:"52.00"
cs_days_to_complete:"120"
days_to_complete:0
description_for_school:""
id:"544"
is_print_only:"0"
logo:"assets/images/new_course.png"
name:"Tennessee"
offer_pdf:"0"
parent_version_id:"0"
pdf_final_price:"0.00"
price:"52"
simple_course:"0"
state_id:"50"
user_in_course:"no"
user_is_waiting:"no"
version_number: "1"
I load the data in a grid like so:
var courses_grid = $("#courses_grid").kendoGrid({
dataSource: {
data: course_data,
schema: {
model: {
fields: {
id: {
type: "number"
},
course_name: {
type: "string"
},
course_short_description: {
type: "string"
}
}
}
},
pageSize: 10,
},
toolbar: kendo.template($("#course-header-template").html()),
rowTemplate: kendo.template($("#rowTemplateCourse").html()),
groupable: false,
sortable: true,
selectable: "single",
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [{
title: "Status",
width: 100
}, {
title: "Course Name",
}]
});
When the page loads, I get an error that course_is_active is not defined. I don't see how it's not defined, as it is clearly here and has a value. Can someone help me figure this out?
More info on the error:
Uncaught ReferenceError: course_is_active is not defined
(function(data
/**/) {
var $kendoOutput, $kendoHtmlEncode = kendo.htmlEncode;with(data){$kendoOutput='\n\t <tr data-cid="'+$kendoHtmlEncode( id )+'" class="course-row" id="course-row'+$kendoHtmlEncode( id )+'">\n <td>\n <span class="circle-indicator label-';if(course_is_active == 1){;$kendoOutput+='success';}else{;$kendoOutput+='danger';};$kendoOutput+='"></span>\n </td>\n\t\t <td>\n '+$kendoHtmlEncode( course_name )+' - '+( name)+'\n\t\t </td>\n\t\t\t<td>\n <span class="badge element-bg-color-blue">ver. '+$kendoHtmlEncode(version_number)+'</span>\n\t\t </td>\n\t </tr>\n\n';}return $kendoOutput;
})
I have found the problem. In my PHP code, I am checking in the arrays if a value is equal to 0 and if it is, I am removing that element from the array. This happens to be the first element in the 2D array I load in the view, so when KendoUI starts to load variables in the table, it starts with the [0] index, that does not exist, and throws an error. Thanks to everyone that participated.
So i am new to kendo controlles in MVC.
I have below .cshtml file.
#(Html.Kendo().Grid<AssetDeprGroupViewModel>()
.Name("AssetDeprGrid")
.Columns(c =>
{
c.Bound(p => p.AssetDeprGroup).Title("Depr Group").HeaderHtmlAttributes(new { style = "text-align: center" }).ClientTemplate("<span title='#=data.AssetDeprGroup#'>#=data.AssetDeprGroup#</span>").Width(85);
c.ForeignKey(p => p.AssetDeprClass, data2).Title("Class").HeaderHtmlAttributes(new { style = "text-align: center" }).Width(53);
c.Group(gr => gr
.Title("AMT").HeaderHtmlAttributes(new { style = "text-align: center" })
.Columns(info =>
{
info.ForeignKey(p => p.MethodAMT, data1).HeaderHtmlAttributes(new { style = "text-align: center" }).Title("Method").Format("{0:p0}").Width(41);
info.ForeignKey(p => p.ConventionAMT, data).HeaderHtmlAttributes(new { style = "text-align: center" }).Title("Convention").Width(41);
info.Bound(p => p.LifeAMT).HeaderHtmlAttributes(new { style = "text-align: center" }).Title("Life").Width(25);
})
);
c.Command(command =>
{
command.Edit(); command.Destroy();
}).Visible(hasCRUDpermission)
.Width(55)
.Title("Action")
.HtmlAttributes(new { style = "text-align: center;" })
.HeaderHtmlAttributes(new { style = "text-align: center;" });
})
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Scrollable()
.DataSource(ds => ds
.Ajax()
.ServerOperation(true)
.Events(e => e.Sync("sync_handler").Change("autoPopulate"))
.Read("GetAssetDeprGroups", "ProjectManagement")
.Create("CreateAssetGroups", "ProjectManagement")
.Update(update=>update.Action("UpdateAssetGroups", "ProjectManagement").Data("additionalInfo"))
.Destroy("DeleteAssetGroups", "ProjectManagement")
So on my change event i am calling below javascript.
function autoPopulate(e) {
if (e.action == 'itemchange' && e.field == 'AssetDeprClass') {
//var grid = $("#AssetDeprGrid").data("kendoGrid");
var assetClassUrl = "#Url.Content("~/ProjectManagement/GetAssetDeprClass")";
var assetClass = $("#AssetDeprClass").val();
$.ajax({
url: assetClassUrl,
type: "POST",
data: { assetClass: assetClass },
success :function(d) {
var classData = d.Data[0];
$("#LifeAMT").val(classData.LifeAMT).toString();
$("#MethodAMT").val(classData.MethodAMT).toString();
$("#ConventionAMT").val(classData.ConventionAMT).toString(); }
});
}
};
The columns are updating fine with the latest data hwen we submit but the columns with foreign key are not reflecting their value on grid dropdown. It shows the same data as previous.
Any solution?
data, data1 and data2 should be Enumerable type and include key and value then you should specify key and value in the ForeignKey column
for example if MethodAMT is your foreignkey:
info.ForeignKey(p => p.MethodAMT, data1 , "MeshodAMT" ,"MeshodAMTTitle").HeaderHtmlAttributes(new { style = "text-align: center" }).Title("Method").Format("{0:p0}").Width(41);
i m using Kendo UI apsnet and i have a Gird with autocomptele as template in 3rd column and i want send data using javascript function "onAutoCompleteX", in this function i want to get id of active autocomplete to send text as parametere to action "GetArticle" but my probleme is how get this id, tried many methods always i get "undefined" or error
#using KendoUIMvcApplication2.Areas.Gescom.Models.Achat
<style>
.k-widget .templateCell
{
overflow: visible;
}
</style>
<script>
function initMenus(e) {
$(".templateCell").each(function () {
eval($(this).children("script").last().html());
});
}
function onAutoCompleteSelectX(e) {
var dataItem = this.dataItem(e.item.index());
var url = '#Url.Action("GetArticle", "Fiche")';
$.ajax({
url: url,
data: { code: dataItem.Code }, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function (data) {
if (data == null)
document.getElementById('labelx').innerHTML = "null";
else
document.getElementById('labelx').innerHTML = data.Code;
},
error: function () {
document.getElementById('labelx').innerHTML = "error";
}
});
}
function onAutoCompleteX() {
var currentId = $(this).attr('id');
//var currentId = $(this).id;
//document.getElementById('labelx').innerHTML = $(this).className; //$obj.attr('id');
return {
text: document.getElementById(currentId).value
//text: $("#id_of_another_autocomplete").val() works fine when i set static id manually
};
}
</script>
<div class="lines-tab-doc">
#(Html.Kendo().Grid<LineAppelOffre>()
.Name("grid-lines-doc")
// Declare grid column
.Columns(columns =>
{
// Cretae all the columns base on Model
columns.Bound(l => l.Document);
columns.Bound(l => l.LigneOriginale);
columns.Template(l => { }).Title(#Resources.Resource.Article)
.HtmlAttributes(new { #class = "templateCell" })
.ClientTemplate(
Html.Kendo().AutoComplete()
.Name("Article")
.HtmlAttributes(new { id = "#=LigneOriginale#", style = "width:100%;" })
.DataTextField("Code")
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetArticles", "Fiche").Data("onAutoCompleteX");
})
.ServerFiltering(true);
})
.Events(e => { e.Select("onAutoCompleteSelectX"); }).ToClientTemplate().ToHtmlString()
);
columns.Bound(l => l.Fournisseur);
columns.Bound(l => l.RefArtFrs);
// Edit and Delete button column
columns.Command(command =>
{
command.Edit();
command.Destroy();
}).Width(200);
})
.Events(ev => ev.DataBound("initMenus"))
// Declare ajax datasource.
// CRUD operation are wired back to ASP MVC Controller/Action e.g. HomeController, GetAll
// Set the model Id
.DataSource(datasoure => datasoure.Ajax()
.Model(model =>
{
//model.Id(l => l.Document);
model.Id(l => l.LigneOriginale);
})
.Read(read => read.Action("LinesAppelOffre_Read", "Achat"))
.Create(create => create.Action("LinesAppelOffre_Add", "Achat"))
.Update(update => update.Action("LinesAppelOffre_Update", "Achat"))
.Destroy(delete => delete.Action("LinesAppelOffre_Delete", "Achat"))
.PageSize(10)
)
// Add tool bar with Create button
.ToolBar(toolbar => toolbar.Create())
// Set grid editable.
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Scrollable(scr=>scr.Height(327))
.Sortable()
.Selectable()
.Navigatable()
.Pageable(pageable =>
{
pageable.Refresh(true);
pageable.PageSizes(true);
pageable.Messages(msg => msg.Empty(null));
})
)
</div>
You can get your AutoComplete id like that:
function onAutoCompleteX(e) {
var currentId = e.sender.element.attr('id');
...
}
But I'm not sure if you have explicity set name as "Article" .Name("Article") you will not always get "Artilcle" as id, even if you set it using .HtmlAttributes property.
If so, just try to use different attribute then id and get is same way.
i used document.activeElement
Browser compatibility
Chrome 2
Firefox (Gecko) 3.0
Internet Explorer 4
Opera 9.6
Safari 4.0
I have got two kendo ui grids (parent grid , child grid) and i have got check box column on parent grid if i click on the checkbox in row in grid, I need to get the corresponding row data and i need to do moving that selected row data to another grid when click on button for that I have implemented button clikc like this ...
For that purpose I have done like this ....
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(document).ready(function ()
{
$('#btnMove').click(function() {
('#GridParent').on("click", "td", function (e) {
var selectedTd = $(e.target).closest("td");
var grdChkBox = selectedTd.parents('tr').find("td:first").next("td").find('input:checkbox');
//grdChkBox.prop('checked', !grdChkBox.prop('checked'));
if(grdChBox.Checked)
{
// here I need to get the checkbox selected item row data
// i dont know it is the correct way to get the item pls correct me
}
var sourcegrid = $('#GridParent').data('kendoGrid');
var destinationgrid = $('#ChildGrid').data('kendoGrid');
var checkeditem =
});
</script>
#model IEnumerable<KendoSampleMVCApp.Models.StudentDetails>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#(Html.Kendo().Grid<KendoSampleMVCApp.Models.StudentDetails>()
.Name("GridParent")
.Columns(columns => {
columns.Bound(p => p.studentclass).HeaderTemplate("<input id='selectall' class='chkbx' type='checkbox' onclick='ToggleChkBox(this.checked);' />").ClientTemplate("<input id='checkbox' onclick='grdChkBoxClick(this); ' class='chkbxq' type='checkbox' />").Sortable(false).Filterable(false).Width(30);
columns.Bound(p => p.studentId).Filterable(false).Width(90);
columns.Bound(p => p.studentName).Filterable(false).Width(90);
columns.Bound(p => p.StudentBranch).Filterable(false).Width(90);
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.Selectable(s => s.Mode(GridSelectionMode.Multiple))
.HtmlAttributes(new { style = "height:250px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Orders_Read", "StudentDtls"))
)
)
<input id="btnMove" type="button" value="Move" />
// second grid .......
I am not sure about the data how can i get when the check box selected
would any one pls help on this ...
Many Thanks .....
In checkbox check select row bind in new grid from controller side. Hope it's working for you
View
#{
ViewBag.Title = "GridListView";
}
<h2>
GridListView</h2>
<script src="~/Script/Jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="~/Script/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<script src="#Url.Content("~/Script/kendo.all.min.js")" type="text/javascript"></script>
<script src="~/Script/kendo.web.min.js" type="text/javascript"></script>
<script src="~/Script/kendo.aspnetmvc.min.js" type="text/javascript"></script>
<link href="~/Content/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo.default.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$('#grid12').on("click", ".chkbxq", function (e) {
var selectedTd = $(this).is(':checked');
var rowIndex = $(this).parent().index();
var cellIndex = $(this).parent().parent().index();
var grid = $("#grid12").data("kendoGrid");
var datatItem = grid.dataItem(grid.tbody.find('tr:eq(' + cellIndex + ')'));
if (selectedTd == true) {
sampleItem = datatItem.SampleItems;
sampleCode = datatItem.SampleCode;
sampledescription = datatItem.SampleDescription;
datavalueitem = sampleItem + "--" + sampleCode + "--" + sampledescription;
$.ajax({
url: '#Url.Action("NewGridView", "Test")',
type: "Post",
data: { sampleItem: sampleItem, sampleCode: sampleCode, sampledescription: sampledescription },
dataType: 'json',
success: function (result) {
debugger;
$("#mygrid").val(null);
var customDataList = $('#grid');
customDataList.empty();
customDataList.append(result.Data);
customDataList.append(result.Data);
$("#divasd").kendoGrid({
dataSource: result,
sortable: true,
pageable: {
refresh: true,
pageSizes: true
},
columns: [
{
field: "SampleDescription",
width: 90,
}, {
field: "SampleCode",
width: 90,
}, {
width: 100,
field: "SampleItems"
}
]
});
}
});
}
});
});
</script>
#using (Html.BeginForm("GridListView", "Test", FormMethod.Post))
{
<input id="Submit1" type="button" value="SubmitValue" />
#(Html.Kendo().Grid<TwoModelInSinglePageModel.SampleModel>()
.Name("grid12")
.Columns(columns =>
{
columns.Bound(p => p.studentclass).HeaderTemplate("<input id='selectall' class='chkbxq' type='checkbox' />").ClientTemplate("<input id='checkbox' class='chkbxq' type='checkbox' />");
columns.Bound(p => p.SampleDescription);
columns.Bound(p => p.SampleCode);
columns.Bound(p => p.SampleItems);
})
.AutoBind(true) // here I am disabling automatic binding at page load
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Read", "Test"))
)
)
<br />
<div id="divasd">
</div>
}
Controller
public JsonResult NewGridView(string sampleItem, string sampleCode, string sampledescription)
{
List<SampleModel> sampleAddList = new List<SampleModel>();
SampleModel sampleAdd = new SampleModel();
sampleAdd.SampleCode = sampleCode;
sampleAdd.SampleDescription = sampledescription;
sampleAdd.SampleItems = sampleItem;
sampleAddList.Add(sampleAdd);
var result = sampleAddList;
return Json(result, JsonRequestBehavior.AllowGet);
}
This bind grid from Controller side
Model
public class SampleModel
{
public bool studentclass { get; set; }
public string SampleDescription { get; set; }
public string SampleCode { get; set; }
public string SampleItems { get; set; }
}