Hello everyone,
So, i want to perform manual paging where i bring data in pages only when user change the page number. I m unable to perform this. Please help me out with this.
note : In below code i have not enabled manual paging as i m confused how to extract parameter from query string and how to bring data only when user switch pages.(server side paging)
Code:
@using Infragistics.Web.Mvc;@using System.Text.Json
@*@model IEnumerable<GridTransaction.Models.Student>*@@* The Ignite UI for MVC Grid data source uses LINQ and therefore only accepts instances of IQueryable<T>. Even when you opt to use the GridMode you will explicitly set the DataSource property which requires an instance of IQueryable<T> .*@
<html><head>
</head><body>
@* @( Html.Infragistics().Grid(Model).ID("grid").PrimaryKey("Id").AutoGenerateColumns(false).Width("100%").AutoCommit(false) .Columns(columns => { columns.For(model => model.Id).DataType("number").HeaderText("Student ID").Width("15%"); columns.For(model => model.Name).DataType("string").HeaderText("Student Name").Width("30%"); columns.For(model => model.Marks).DataType("number").HeaderText("Marks").Width("30%"); columns.For(model => model.subject).DataType("string").HeaderText("Subject").Width("15%"); columns.For(model => model.Imagepath).DataType("string").HeaderText("Imagepath").Template("<img src='${Imagepath}' width='50' height='50' />"); }).DataSource(Model) // Set the data source URL .Features(features => { features.Selection().MultipleSelection(true); features.GroupBy(); features.Paging().PageSize(10); features.Updating(); features.Tooltips().Visibility(TooltipsVisibility.Always);// provide informaion about grid when you hover over features.RowSelectors().EnableCheckBoxes(true); features.RowSelectors().EnableRowNumbering(true); features.Updating().EnableAddRow(true).EnableDeleteRow(true); features.Sorting().Type(OpType.Remote).SortUrlKey("hi");
features.Updating().ColumnSettings(set => { set.ColumnSetting().ColumnKey("Id").ReadOnly(true); }); features.Filtering(); }).UpdateUrl(Url.Action("put")) .ResponseContentType("Json") .UpdateUrl(Url.Action("put")) .DataBind() .Render() ) *@
<div> <table id="grid">
</table> </div>
<div class="text-center"> <button id="savechanges" class="btn btn-primary">Save</button> </div>
</body></html>
@section scripts{
@*Batch Update*@<script> $(function () { $("#grid").igGrid({ primaryKey: "id", renderCheckboxes: true, autoGenerateColumns: false, updateUrl: "/Student/put/", width: "100%", columns: [ { headerText: "Student ID", key: "id", dataType: "number", width: "15%" }, { headerText: "Student Name", key: "name", dataType: "string", width: "30%" }, { headerText: "Marks", key: "marks", dataType: "number", width: "30%" }, { headerText: "Image", key: "imagepath", dataType: "string", width: "15%", template: "<img src='${imagepath}' width='50' height='50' />" }, { headerText: "Subject", key: "subject", dataType: "string", width: "15%" } ], dataSourceUrl: "/Student/Data12", dataSource: "/Student/Data", features: [ { name: "Selection", mode: "row", multipleSelection: true }, { name: "RowSelectors", enableCheckBoxes: true, enableRowNumbering: true }, { name: "GroupBy" }, { name :"Paging", type:"local", pageSize : 7 }, { name: "Filtering", type:"remote", filterExprUrlKey: "filter", columnSettings: [ { columnKey: "selectColumn", allowFiltering: false } ] }, { name: "Sorting", type: "remote", // sortUrlKey: 'sort', // sortUrlKeyAscValue: 'asc', // sortUrlKeyDescValue: 'desc' }, { name: "Updating", enableAddRow: true, editMode: "row", validation: true, enableDeleteRow: true, rowAdded: function (evt, ui) { // Custom logic to execute when a row is added console.log("Event arguments (ui):", ui); console.log("Row data:", ui.rowId); console.log(typeof (ui.values)); }, columnSettings: [ { columnKey: "id", readOnly: true }, { columnKey: "name", editorType: "text", validation: true, editorOptions: { validatorOptions: { required: { errorMessage: "You must enter a value to submit."
}, custom: function(ui,evt){ var validator = $("#grid").igGridUpdating("editorForKey", "name").data("igValidator").element; console.log(validator); if (ui == "rohit") { $(validator).igValidator("option", "errorMessage", "cant enter name rohit"); return false; } return true;
} } } }, { columnKey: "marks", editorType: "number", validation: true, editorOptions: { validatorOptions: { required: { errorMessage: "You must enter a value to submittt."
}, custom:function(ui,evt){ console.log(ui); console.log("hi"); if (ui >= 50) { var validator1 = $("#grid").igGridUpdating("editorForKey", "imagepath").data("igValidator").element; // var validator11 = $("#grid").igGridUpdating("editorForKey", "imagepath"); // console.log(validator11); // console.log("hi"); // console.log(validator11);
// var validator12 = $("#grid").igGridUpdating("editorForKey", "imagepath").data("igValidator");
// console.log(validator12);
//Set $(validator1).igValidator("option", "required", true);
$(validator1).igValidator("option", "errorMessage", 'This field is required for marks between 50-100');
return true; } else { var validator1 = $("#grid").igGridUpdating("editorForKey", "imagepath").data("igValidator").element;
//Set $(validator1).igValidator("option", "required", false);
return true; } } } } } ] } ] });
$("#savechanges").on("click", function () { alert("Save button clicked"); // Save changes when the button is clicked $("#grid").igGrid("saveChanges"); }); });
</script>
} ASP CODE TO HANDLE PAGING:
public JsonResult Data12() {
var absolutepath1 = HttpContext.Request.QueryString.ToString(); var absolutepath = HttpContext.Request.Query["$orderby"].ToString();
Console.WriteLine(absolutepath1);
string[] m = absolutepath.Split(' '); //foreach(var m2 in m) //{ // Console.WriteLine(m2); //} // absolutepath.Remove("?");
var colname = m[0]; var orderb1y = m[1];
IEnumerable<Student> sat = data.sort(colname, orderb1y);
// IEnumerable<Student> students = data.GetStudents();
return Json(sat);
Hello Rohit,
In order for you to further test the sample and compare the different parts to your own project, i.e., igGrid configuration, required jQuery and Ignite UI for jQuery js and css files, custom paging methods configuration, etc., I am applying a working MVC project.
Please review the code configuration, test it on your side and let me know if you need any further assistance regarding this matter.
Sincerely, Riva Ivanova Associate Software Developer
4152.igGrid Remote Paging MVC.zip
Hello Riya,
I tried the same thing in my code still it doesnt work.Getting this error.
I m sharing my code below. Can you please let me know what am i doing wrong?Controller:
[GridDataSourceAction] public IActionResult Index() {
var absolutepath1 = Request.QueryString.Value; Console.WriteLine(absolutepath1); return View(); }
public JsonResult Data() {
var absolutepath1 = Request.QueryString.Value; NameValueCollection parse1 = HttpUtility.ParseQueryString(absolutepath1); int skip = Convert.ToInt32(parse1["$skip"]);//number of rows to skip int top = Convert.ToInt32(parse1["$top"]);// entries to be displayed
if (skip != null && top != null) {
IEnumerable<Student> s12 = data.GetStudents(); IEnumerable<Student> page = s12.Skip(skip).Take(top).ToList(); // var result = new JsonResult(new { Records = s12 , TotalRecordsCount = 77 }); JsonResult result = new JsonResult(new { }, new JsonSerializerOptions { PropertyNamingPolicy = null }); result.Value = new { Records = page, TotalRecordsCount =s12.Count() }; return result;
}
return Json(data.GetStudents());
}:
@*Batch Update*@<script> $(function () { $("#grid").igGrid({ primaryKey: "id", autoGenerateColumns: false, updateUrl: "/Student/put/", width: "100%",
responseDataKey: 'Records', columns: [ { headerText: "Student ID", key: "id", dataType: "number", width: "10%" }, { headerText: "Student Name", key: "name", dataType: "string", width: "20%" }, { headerText: "Marks", key: "marks", dataType: "number", width: "30%" }, { headerText: "Image", key: "imagepath", dataType: "string", width: "15%", template: "<img src='${imagepath}' width='50' height='50' />" }, { headerText: "Subject", key: "subject", dataType: "string", width: "15%" } ], dataSourceUrl: "/Student/Data12", dataSource: "/Student/Data", features: [ { name: 'Paging', recordCountKey: 'TotalRecordsCount', pageSize: 5, type: 'remote', } ] })
This is my code. if you need anything else please do let me know.
Thank you for your follow-up message!
I have been looking into your additional questions and the provided code what I can assume regarding the following error:
is the following line of code:
I am not sure what the custom data.GetStudents() method returns, , however, the igGrid is configured with responseDataKey: 'Records' and the igGridPaging feature is configured with recordCountKey: 'TotalRecordsCount' which expects the HTTP response to contain these properties in order for the grid to be rendered correctly.
On my side, I was able to reproduce the described behavior by testing the following line of code return Json(data.GetStudents()); with some custom method that returns a list of records. In this case, the JsonResult object’s Value property contains only Count, however, it should contain Records and TotalRecordsCount.
Having this in mind, what I would suggest is performing the paging operation by reassigning the data and setting the JsonResult object at the end of your custom public JsonResult Data() method.
For example, this could look similar to the following:
public JsonResult Data() { var absolutepath1 = Request.QueryString.Value; NameValueCollection parse1 = HttpUtility.ParseQueryString(absolutepath1); int skip = Convert.ToInt32(parse1["$skip"]);//number of rows to skip int top = Convert.ToInt32(parse1["$top"]);// entries to be displayed IEnumerable<Student> s12 = data.GetStudents(); int totalCount = s12.Count(); if (skip != null && top != null) { s12 = s12.Skip(skip).Take(top); } JsonResult result = new JsonResult(new { }, new JsonSerializerOptions { PropertyNamingPolicy = null }); result.Value = new { Records = s12, TotalRecordsCount = totalCount }; return result; }
Please test it on your side and let me know how it behaves.
Regarding your additional questions:
(1) Idk why but as soon as i change autoGenerateColumns to true its working else its not working showing the above error. Why is that happening.
(2) but when i turn autogenerate columns off and remove width from columns its generating extra columns which arent even in my column field . Why is this happening
On my side, I was not able to reproduce such behavior, however, this may be due to the differences in the project configurations.
Having this in mind, if the above suggestion does not resolve your query, in order to assist you further, it would be highly appreciated if you could provide me with a small, isolated sample with some test data that demonstrates the behavior on your side. Remove any external dependencies and code that is not directly related to the issue, zip your application and attach it in this forum thread.
This would be extremely helpful in further investigating this matter and providing you with a solution as soon as possible.
Thank you for your cooperation.
how to insert a zip here? I cant find the option.
(1) Did you have the chance to inspect the response from the request in order to determine if it is in the correct format?
This could be done with right mouse click -> Inspect -> Network tab -> YOUR_REQUEST_NAME -> Response tab
It should contain the Records (array of objects) and TotalRecordsCount (number) properties in order to be considered a correct format.
I am asking this question because this error most commonly is due to the response format not matching the defined schema (the responseDataKey: 'Records')
This is also mentioned in our Handling Remote Features Manually topic here:
Note that the property holding the data should match the responseDataKey option defined on the client-side and the property holding the total count should match the recordCountKey option of the Paging feature.
Additionally, I have noticed that you are setting both the dataSource and the dataSourceUrl options. In the Handling Remote Features Manually sample here as well as the provided by me sample here, only the dataSource option is set and when performing paging, sorting, filtering, etc., the requests are only sent to the method specified in the dataSource option.
(2) Is there any specific reason for having both options set?
If not, I would suggest removing the dataSourceUrl option since initially and on every other interaction the request is sent to the dataSource: "/Student/Data" method which, as previously mentioned, should return a response in the correct format. Having this in mind, using return Json(data.GetStudents()); is not an option since the response format is not correct. Try this one instead:
JsonResult result = new JsonResult(new { }, new JsonSerializerOptions { PropertyNamingPolicy = null }); result.Value = new { Records = MODIFIED_DATA_HERE, TotalRecordsCount = TOTAL_COUNT_HERE }; return result;
Setting the result.Value as demonstrated in the above code will ensure that your response has the correct format.
If you require using the dataSourceUrl option as well, then the above is also valid for the dataSourceUrl: "/Student/Data12" method – you should return a JsonResult that includes the Records (array of objects) and TotalRecordsCount (number) properties.
Please test this approach on your side and if you continue to experience this behavior, inspect the received response. It should be in a format similar to this one:
{ "Records": [ { "ID": 1, "FirstName": "John", "LastName": "Doe", "Country": "USA", "Age": 25 }, { "ID": 2, "FirstName": "Jane", "LastName": "Doe", "Country": "Canada", "Age": 26 }, ... ], "TotalRecordsCount": 20 }
If the Records key is misspelled ("records", "RECORDS", etc.), or missing, then it could be concluded that this is the reason for this behavior and the returned JsonResult format in the custom /Student/Data and /Student/Data12 methods should be changed as suggested.
To conclude, as the provided by me sample seems to be working correctly and cannot reproduce the described behaviors, I would suggest referencing it and comparing the different parts to your own project. Also, I would suggest referring to our Handling Remote Features Manually topic as well.
Let me know if you need any further assistance regarding this matter.
I am unable to attachment as I did this sample project in my work laptop it wont allow me to share the zip.I cant even share this file to my personal mail even when its my personal practice project,Is there any way you could help as i cannot share the zip.
Attaching a .zip file or any other could be achieved by:
(1) Clicking the Insert button
(2) Clicking the Insert image/video/file button
(3) Changing the From section to File Upload.
(4) Clicking the Browse button in the File section
Then you will be able to navigate to your zip file and attach it in this forum thread.