Kendo Grid not Paging data - kendo-ui

I use Kendo Grid for my ASP.NET MVC app which uses ajax binding for the read.
It binds the data to the first page but does not show the number pages for the grid.
it shows (|< < 0 > >|).
Index.cshtml
#(Html.Kendo().Grid<Club.Areas.Admin.Models.Users>()
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("List1", "Home"))
.PageSize(5)
)
.Columns(columns =>
{
columns.Bound(p => p.Id).Filterable(false).Width(100);
columns.Bound(p => p.NickName).Width(100);
columns.Bound(p => p.UserVisitLastDate).Format("{0:MM/dd/yyyy}").Width(140);
columns.Bound(p => p.Mobile).Width(100);
})
.Pageable()
.Sortable()
.HtmlAttributes(new { style = "width:500px;height:430px;" })
)
HomeController
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult List1([DataSourceRequest]DataSourceRequest request)
{
List<Users> U = new List<Users>();
for (int i = 0; i < 100; i++)
{
U.Add(new Users
{
NickName = "Mehdi",
Company = "Taral",
Email = "M.Farokhtabar#Gmail.com",
Family = "FT",
HomeAddress = "Isfahan",
HomePhone = "03112332940",
IsActive = true,
Mobile = "09131025834",
Name = "Mehdi",
UserCreateDate = DateTime.Now,
UserVisitLastDate = DateTime.Now,
WebSite = "",
WorkAddress = "Mehdi",
PostalCode = "1234567890",
Id = i,
WorkPhone = "03117726250"
});
}
DataSourceResult result = U.ToDataSourceResult(request);
return Json(result,JsonRequestBehavior.AllowGet);
}
}

You will have to set serverPaging: true of the DataSource and make sure that the response from server has total field with the amount of the items.

My answer is not completely related to MVC approach, I have used this with WebAPI controller. The datasource should look something like this:
var sampleDataSource = new kendo.data.DataSource({
transport: {
read: {
url: svcSampleUrl,
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json"
},
parameterMap: function (options) {
model.Take = options.take;
model.Skip = options.skip;
model.Sort = options.sort;
model.Filter = options.filter;
return kendo.stringify(model);
}
},
schema: {
data: "sampleDTOList",
total: "totalItems",
model: {
fields: {
ID: { type: "number" },
Label: { type: "string" },
Description: { type: "string" }
}
}
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
The total attribute in the schema is where it gets the total number of records and calculates the number of pages to show. In your case you are receiving the data of the first page, and the grid does not know how much data there is in order to calculate the total number of pages there needs to be.

Related

How does the model structure look like for Kendo TreeView, to bind remote data?

How does the model structure look like for Kendo TreeView, to bind remote data
We have a tree displaying system locations which have hierarchical structure. We use the following code:
C# code:
[HttpPost]
public async Task<ActionResult> GetChildrenAsync(long? parentId)
{
//retrieving location's children by parentId
//DTO has ChildrenCount field that shows how many children has any particular location
return new JsonResult
{
Data = locations.Select(x => new
{
LocationId = x.Id,
Name = x.Name,
HasChildren = x.ChildrenCount > 0
}),
MaxJsonLength = Int32.MaxValue
};
}
JS code:
var locationDataSource = new kendo.data.HierarchicalDataSource({
transport: {
type: "json",
read: {
url: "#Url.Action("GetChildren", "Location")",
type: "POST"
},
parameterMap: function (data) {
return { parentId: data.LocationId };
}
},
schema: {
model: {
id: "LocationId",
hasChildren: "HasChildren"
}
}
});
var kendoTree = $("#location-tree").kendoTreeView({
dataSource: locationDataSource,
dataTextField: "Name"
});

Kendo Grid Aggregate Sum Displaying always 0

I have Combobox event that call ajax function to fill grid datasource.
i can see my grid correctly filled but aggregate Sum display always 0.
What can i do?
AJAX call
$.ajax({
url: '#Url.Action("CreaGrid3", "Sales")',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { bra: brand, mod: model, prj: project, ver: version, rel: release },
success: function (result) {
var grid = $("#Grid3").data("kendoGrid");
var dataSource = new kendo.data.DataSource({
data: result.Data
});
grid.setDataSource(dataSource);
grid.dataSource.read();
}
Here my view:
#(Html.Kendo().Grid<IndSudUI.Models.TabTemp3>()
.Name("Grid3")
.Columns(columns =>
{
columns.Bound(e => e.DESCRIZIONE);
columns.Bound(e => e.Totale)
.Format("{0:C3}")
.ClientFooterTemplate("Sum: #=sum#");
})
.Pageable()
.Sortable()
.Scrollable()
.Resizable(resize => resize.Columns(true))
.DataSource(dataSource => dataSource
.Ajax()
.Aggregates(a =>
{
a.Add(p => p.Totale).Sum();
})
.ServerOperation(false)
)
.Events(events => events.DataBound("onDataBound5"))
)
Here my Controller
I removed some parts of code that are not relevant
public JsonResult CreaGrid3([DataSourceRequest] DataSourceRequest request, string bra, string mod, string prj, string ver, string rel)
{
if (!String.IsNullOrEmpty(bra))
bra = bra.Trim();
if (!String.IsNullOrEmpty(mod))
mod = mod.Trim();
if (!String.IsNullOrEmpty(prj))
prj = prj.Trim();
if (!String.IsNullOrEmpty(ver))
ver = ver.Trim();
if (!String.IsNullOrEmpty(rel))
rel = Convert.ToDateTime(rel.Trim()).ToString("yyyyMMdd");
try
{
List<TabTemp3> Listed = new List<TabTemp3>();
var connection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
DataTable dt = new DataTable();
string sqlcmd = "SELECT l.DESCRIZIONE, CASE WHEN m.PezziTurnoStd=0 THEN 0 ELSE (8 / CONVERT(decimal, m.PezziTurnoStd)) * pr.CostoOraDir * m.PersonaleDirettoStd END Totale FROM ";
sqlcmd = sqlcmd + "AHE.dbo.Inds0DbParArt AS m INNER JOIN ";
//... ETC ...
using (var dataAdapter = new SqlDataAdapter(sqlcmd, connection))
{
dataAdapter.Fill(dt);
}
foreach (DataRow row in dt.Rows)
{
Listed.Add(new TabTemp3
{
DESCRIZIONE = row["DESCRIZIONE"].ToString(),
Totale = (decimal)(row["Totale"])
});
}
var temp = Listed.AsEnumerable<TabTemp3>();
return Json(temp.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("" + e);
}
return null;
}

Internal Server Error on kendo grid update with ajax

i m trying to update grid with ajax but i couldn't success in passing and getting values between controler and view with ajax
When i run program its output is like that
[object Object]++error++Internal Server Error
So i need help
HomeController Function
[HttpGet]
public ActionResult RssCek(string value)
{
XDocument rssXml = new XDocument();
switch (value)
{
case "Ekonomi":
{
rssXml = XDocument.Load("http://sozcu.com.tr/rss.php");
break;
}
case "Siyaset":
{
rssXml = XDocument.Load("http://www.milliyet.com.tr/D/rss/rss/Rss_4.xml");
break;
}
case "Yaşam":
{
rssXml = XDocument.Load("http://www.milliyet.com.tr/D/rss/rss/Rss_5.xml");
break;
}
default:
{
rssXml = XDocument.Load("http://sozcu.com.tr/rss.php");
}
break;
}
var feedler = from feed in rssXml.Descendants("item")
select new Rss
{
Baslik = feed.Element("title").Value,
Link = "Oku",
Aciklama = feed.Element("description").Value
};
var valueToReturn = new JsonResult { Data = feedler };
return valueToReturn;
}
IndexView Grid Code
#Html.Kendo().Grid(Model)
.Name("Grid").Pageable()
.Columns(columns =>
{
columns.Bound(p => p.Baslik).Groupable(false);
columns.Bound(p => p.Aciklama).Encoded(false);
columns.Bound(p => p.Link).Encoded(false);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("RssCek", "Home"))
)
IndexView JavaScript Code
<script>
function select(e) {
var value = $(e.item).find("> .k-link").text();
$.ajax({
url: '#Url.Action("RssCek", "Home")',
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: { value: value},
success: function (feedler)
{
document.write(feedler);
},
error: function (request, status, error)
{document.write(request+"++"+ status+"++"+ error);}
});
}
</script>
I found problem is caused by missing JsonRequestBehavior.AllowGet
return Json(feedler, JsonRequestBehavior.AllowGet);
instead of ;
var valueToReturn = new JsonResult { Data = feedler };
return valueToReturn;

Kendo grid gets null object on create/update/delete

I tried a simple Kendo UI grid with CRUD operations with an Employee class. But when I create/update/delete, the employee object in the controller doesn't get the respective value and Id sets to 0 on all the operations
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "Components/",
dataSource = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
url: crudServiceBaseUrl + "GetEmployees",
dataType: "json"
},
update: {
url: crudServiceBaseUrl + "UpdateEmployee",
dataType: "json",
type: "Post"
},
destroy: {
url: crudServiceBaseUrl + "DeleteEmployee",
dataType: "json",
type: "Post"
},
create: {
url: crudServiceBaseUrl + "CreateEmployee",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
},
parameterMap: function (data, type) {
return kendo.stringify(data);
},
},
batch: true,
pageSize: 20,
type: "json",
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
Id: { editable: false, nullable: true },
FullName: { validation: { required: true } },
Designation: { validation: { required: true } },
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
toolbar: ["create"],
columns: [
{ field: "Id" },
{ field: "FullName" },
{ field: "Designation" },
{ command: ["edit", "destroy"], title: " ", width: "160px" }],
editable: "popup"
});
});
</script>
and here are the controller actions.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateEmployee([DataSourceRequest] DataSourceRequest request, Employee employee)
{
if (employee != null && ModelState.IsValid)
{
using (EmployeeDBDataContext context = new EmployeeDBDataContext())
{
EmployeeTable newEmployee = new EmployeeTable();
newEmployee.FullName = employee.FullName;
newEmployee.Designation = employee.Designation;
context.EmployeeTables.InsertOnSubmit(newEmployee);
context.SubmitChanges();
}
}
return Json(new[] { employee }.ToDataSourceResult(request, ModelState));
}
public ActionResult GetEmployees([DataSourceRequest] DataSourceRequest request)
{
var lstConfiguredEmails = new List<Employee>();
using (EmployeeDBDataContext context = new EmployeeDBDataContext())
{
lstConfiguredEmails = (from e in context.EmployeeTables
select new Employee
{
Id = e.Id,
FullName = e.FullName,
Designation = e.Designation
}).ToList();
}
return Json(lstConfiguredEmails.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteEmployee([DataSourceRequest] DataSourceRequest request, Employee employee)
{
if (employee != null)
{
using (EmployeeDBDataContext context = new EmployeeDBDataContext())
{
EmployeeTable deleteEmployee = (from e in context.EmployeeTables
where e.Id == employee.Id
select e).SingleOrDefault();
context.EmployeeTables.DeleteOnSubmit(deleteEmployee);
context.SubmitChanges();
}
}
return Json(ModelState.ToDataSourceResult());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateEmployee([DataSourceRequest] DataSourceRequest request, Employee employee)
{
if (employee != null && ModelState.IsValid)
{
using (EmployeeDBDataContext context = new EmployeeDBDataContext())
{
EmployeeTable updateEmployee = (from e in context.EmployeeTables
where e.Id == employee.Id
select e).SingleOrDefault();
updateEmployee.Id = employee.Id;
updateEmployee.FullName = employee.FullName;
updateEmployee.Designation = employee.Designation;
context.SubmitChanges();
}
}
return Json(ModelState.ToDataSourceResult());
}
and the model class
public class Employee
{
public int Id { get; set; }
public string FullName { get; set; }
public string Designation { get; set; }
}
Everytime on pressing Create/Update/Detele, the employee value in controller actions comes as,
Id = 0;
FullName = null;
Designation = null;
Please give solution.
When I used tbe grid with the code below
#(Html.Kendo().Grid<Employee>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.Id);
columns.Bound(p => p.FullName);
columns.Bound(p => p.Designation);
columns.Command(command => { command.Edit(); command.Destroy(); }).Width(160);
})
.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.Id))
.Create(update => update.Action("CreateEmployee", "Components"))
.Read(read => read.Action("GetEmployees", "Components"))
.Update(update => update.Action("UpdateEmployee", "Components"))
.Destroy(update => update.Action("DeleteEmployee", "Components"))
)
)
it works perfectly with the same controller actions.
The issue is resolved by removing batch: true from Datasource.
Try setting transport.create.contentType to "application/json". It might just be that it is sending the server the wrong content type so the server doesn't know how to parse it.

Paging/Sorting not working on web grid used in Partial View

I have a partial view where I am showing a web grid depending upon a value selected from a page.
For drop down I have used
#Html.DropDownListFor(
x => x.ItemId,
new SelectList(Model.Items, "Value", "Text"),
new {
id = "myddl",
data_url = Url.Action("Foo", "SomeController")
}
)
For drop down item select I have used
$(function() {
$('#myddl').change(function() {
var url = $(this).data('url');
var value = $(this).val();
$('#result').load(url, { value: value })
});
});
and below is my action
public ActionResult Foo(string value)
{
SomeModel model = ...
return PartialView(model);
}
everything works good, but when I try doing a paging or sorting on my webgrid which is on my partial view I am showing a new window with the web grid.
I wanted to be able to sort and page on the same page without postback
Please help
The following example works fine for me.
Model:
public class MyViewModel
{
public string Bar { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Foo(string value)
{
var model = Enumerable.Range(1, 45).Select(x => new MyViewModel
{
Bar = "bar " + value + " " + x
});
return PartialView(model);
}
}
Index.cshtml view:
<script type="text/javascript">
$(function () {
$('#myddl').change(function () {
var url = $(this).data('url');
var value = $(this).val();
$.ajax({
url: url,
type: 'GET',
cache: false,
data: { value: value },
success: function (result) {
$('#result').html(result);
}
});
});
});
</script>
#Html.DropDownList(
"id",
new[] {
new SelectListItem { Value = "val1", Text = "value 1" },
new SelectListItem { Value = "val2", Text = "value 2" },
new SelectListItem { Value = "val3", Text = "value 3" },
},
new {
id = "myddl",
data_url = Url.Action("Foo", "Home")
}
)
<div id="result">
#Html.Action("Foo")
</div>
Foo.cshtml partial:
#model IEnumerable<MyViewModel>
#{
var grid = new WebGrid(
canPage: true,
rowsPerPage: 10,
canSort: true,
ajaxUpdateContainerId: "grid"
);
grid.Bind(Model, rowCount: Model.Count());
grid.Pager(WebGridPagerModes.All);
}
#grid.GetHtml(
htmlAttributes: new { id = "grid" },
columns: grid.Columns(
grid.Column("Bar")
)
)
Notice that I have used a GET request to refresh the grid instead of POST because this way the value query string parameter selected in the dropdown is preserved for future sorting and paging.

Resources