In this article, we are going to learn how to use jqGrid with ASP.NET MVC along with we are going to use Entity framework for accessing the database.
If you belong to a background of ASP.NET web forms, then there is grid view which we used most but in some scenarios, if the data was large, then it would use to break. However, in MVC, we do not have that kind of grid which has all readymade events but there is HTML helper which helps you to generate the HTML in Web grid. In that, we need to use different packages for handling paging of the grid, and also, we need to pass a strongly typed model to view for rendering the grid.
Now, if we want a Grid which is lighter and easy to use, in that grid, we can do paging, search, and create a new record, Edit record, delete record easily, then we are going to use it right.
Let’s start with database part first.
Database Part
I have created a database with the name “Northwind” and in that, it has “Customers” table.
Next, we are going to create an ASP.NET MVC5 Web application.
Creating ASP.NET MVC5 Web Application
Open New Visual Studio 2015 IDE.
After opening IDE just, next we are going to create MVC project for doing that just click File - inside that New - Project.
After choosing a project, a new dialog will pop up with the name “New Project”. In that, we are going to choose Visual C# Project Templates >> Web >> ASP.NET Web Application. Then, we are going to name the project as “DemoGrids”.
After naming the project we are going click on OK button to create a project.
A new dialog will pop up for choosing templates for Creating “ASP.NET Web Application;” in that template, we are going to Create MVC application. That's why we are going to choose “MVC template” and next click on OK button to create a project.
After clicking on OK button it will start to create a project.
Project Structure
After creating project next we are going to create Model.
Creating Customer Model
We are going to add Customer Model to the Models folder.
- [Table("Customers")]
- public class Customers
- {
- [Key]
- public int? CustomerID { get; set; }
- [Required(ErrorMessage = "Required CompanyName")]
- public string CompanyName { get; set; }
- [Required(ErrorMessage = "Required ContactName")]
- public string ContactName { get; set; }
- [Required(ErrorMessage = "Required ContactTitle")]
- public string ContactTitle { get; set; }
- public string Address { get; set; }
- [Required(ErrorMessage = "Required City")]
- public string City { get; set; }
- public string Region { get; set; }
- [Required(ErrorMessage = "Required PostalCode")]
- public string PostalCode { get; set; }
- [Required(ErrorMessage = "Required Country")]
- public string Country { get; set; }
- [Required(ErrorMessage = "Required Phone")]
- public string Phone { get; set; }
- public string Fax { get; set; }
- }
After adding model next we are going to use Entity framework for accessing database to doing that we need to setup DbContext class.
Note
What is DbContext?
DbContext is an important part of Entity Framework.
It is a bridge between your domain or entity classes and the database.
DbContext is the primary class that is responsible for interacting with data as an object.
Referenced from: - http://www.entityframeworktutorial.net/EntityFramework4.3/dbcontext-vs-objectcontext.aspx
Setting up DbContext Class
In this part, we are first going to create a class with name “DatabaseContext” and this class will be inheriting from “DbContext” class.
We are going create this class in Model Folder.
Note
“DBConnection” is Connection string name.
Note
What is DBSet?
Referenced from: - http://www.entityframeworktutorial.net/EntityFramework4.3/dbsetclass.aspx
DBSet class represents an entity set that is used for creating, read, update, and delete operations. A generic version of DBSet (DbSet<TEntity>) can be used when the type of entity is not known at build time.
After adding “DatabaseContext” class next we are going to inherit this class with “DbContext” class.
After inheriting class next in constructor we are going to create a connection for doing that we need to pass connection string name to “DbContext” class, we are passing connection string name as DBConnection.
After passing connection string next we are going to declare DbSet in “DbContext” class which will help us to perform create, read, update, and delete operations.
Code Snippet
- using System.Data.Entity;
-
- namespace DemoGrids.Models
- {
- public class DatabaseContext : DbContext
- {
- public DatabaseContext() : base("DBConnection")
- {
- }
-
- public DbSet<Customers> Customers { get; set;}
- }
- }
Connection string in Web.config file
- <connectionStrings>
- <add name="DBConnection"
- connectionString="Data Source=####; initial catalog=Northwind; user id=sa; password=Pass####;"
- providerName="System.Data.SqlClient" />
- </connectionStrings>
After setting up DbContext class next we are going to add jQuery.jqGrid package from NuGet packages.
Adding jQuery.jqGrid from NuGet packages
For adding jQuery.jqGrid Reference from NuGet package just right click on the project a list will populate in that just choose Manage NuGet Packages a new dialog will popup of NuGet in that there is Browse option with search, just search jQuery.jqGrid and from search result choose “jQuery.jqGrid” package and click on Install button, this package will add CSS and jQuery files required for the jqGrid grid.
After installing jqGrid below is project structure which shows jqGrid grid reference is added to Content and Scripts folder.
Next, we are going to add a controller.
Adding DemoController
In this part, we are going to add a controller with a name as “Demo”.
Next, after adding Controller, we are going to get a Default Action method with name Index, this View we are going add for displaying Grid, Along with that we need to add another Action Method for handling Ajax Get Request for Getting Data and binding it to Grid.
Adding Action Method GetCustomer
This Action Method will return a JSON object that is required for binding data to gird.
Adding GetCustomers Action Method which will take few parameters as input for handling (sorting, Paging, and searching in the grid).
-
- public JsonResult GetCustomers(string word, int page, int rows, string searchString)
- {
-
- using (DatabaseContext db = new DatabaseContext())
- {
-
- int pageIndex = Convert.ToInt32(page) - 1;
- int pageSize = rows;
-
-
- var Results = db.Customers.Select(
- a => new
- {
- a.CustomerID,
- a.CompanyName,
- a.ContactName,
- a.ContactTitle,
- a.City,
- a.PostalCode,
- a.Country,
- a.Phone,
- });
-
-
- int totalRecords = Results.Count();
- var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
-
-
- if (sord.ToUpper() == "DESC")
- {
- Results = Results.OrderByDescending(s => s.CustomerID);
- Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
- }
- else
- {
- Results = Results.OrderBy(s => s.CustomerID);
- Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
- }
-
- if (!string.IsNullOrEmpty(searchString))
- {
- Results = Results.Where(m => m.Country == searchString);
- }
-
- var jsonData = new
- {
- total = totalPages,
- page,
- records = totalRecords,
- rows = Results
- };
- return Json(jsonData, JsonRequestBehavior.AllowGet);
- }
- }
Understanding Code Snippet.
- The first step we are going to create Instance of DatabaseContext for accessing Database.
- Second step setting page index on bases of Parameter which we receive from the request.
- The third Step we are going write Linq Query for Getting Data from Database which we are going to store in Result variable it is in IQueryable form.
- Fourth step we are going to calculate Total Records and Total Pages which we need to send it to View.
- Fifth Step Setting Sorting Order.
- Six Step Setting Search for Grid.
- Final Step in this step we are going to Collect all variable and send them to View in JSON Format.
After adding and Understanding GetCustomer Action Method next we are going to add View for Index Action Method which was default created while creating Controller.
Adding Index View to Index Action Method
In this part, we are going to add Index View.
Project structure after adding Index view.
Next, we are going to add jqGrid Script and CSS reference to Index View.
Adding Script and CSS reference of jqGrid to Index View
In this step, we are going to add jqGrid Script and CSS reference to index view.
This script is added to project when we add jqGrid Grid from NuGet package.
- <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
- <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/jquery-ui-1.10.0.js"></script>
- <script src="~/Scripts/i18n/grid.locale-en.js"></script>
- <script src="~/Scripts/jquery.jqGrid.min.js"></script>
Adding empty <table> element
After adding Scripts and Css next we need to add table element for reserve the place where the grid should be created.
- <table id="Demogrid"></table>
Next step we are going to show simple grid with Customers columns in it.
Creating jqGrid
In this part, we are going to write a script to create JqGrid and to call Action Method “GetCustomers” to get data to bind to the grid.
Code Snippet
- <script>
- $(function () {
- debugger;
- $("#Demogrid").jqGrid
- ({
- url: "/Demo/GetCustomers",
- datatype: 'json',
- mtype: 'Get',
-
- colNames: ['CustomerID', 'CompanyName', 'ContactName',
- 'ContactTitle', 'City', 'PostalCode', 'Country', 'Phone'],
-
- colModel: [
- { name: "CustomerID" },
- { name: "CompanyName" },
- { name: "ContactName" },
- { name: "ContactTitle" },
- { name: "City" },
- { name: "PostalCode" },
- { name: "Country" },
- { name: "Phone" }
- ],
- height: '100%',
- rowNum: 10,
- viewrecords: true,
- caption: 'JQgrid DEMO',
- emptyrecords: 'No records',
- jsonReader:
- {
- root: "rows",
- page: "page",
- total: "total",
- records: "records",
- repeatitems: false,
- Id: "0"
- },
- autowidth: true,
- });
- });
- </script>
JqGrid options
Referenced from - http://www.trirand.com/jqgridwiki/doku.php?id=wiki:first_grid
Property | Description |
url | Tells us where to get the data. Typically this is a server-side function with a connection to a database which returns the appropriate information to be filled into the Body layer in the grid |
datatype | This tells jqGrid the type of information being returned so it can construct the grid. In this case, we tell the grid that we expect XML data to be returned from the server, but other formats are possible. For a list of all available datatypes refer to API Methods |
mtype | Tells us how to make the Ajax call: either 'GET' or 'POST'. In this case, we will use the GET method to retrieve data from the server |
colNames | An array in which we place the names of the columns. This is the text that appears in the head of the grid (Header layer). The names are separated by commas |
colModel | An array that describes the model of the columns. This is the most important part of the grid. Here I explain only the options used above. For the complete list of options see colModel API name: The name of the column. This name does not have to be the name of the database table, but later we will see how we can use this when we have different data formats. index: The name passed to the server on which to sort the data (note that we could pass column numbers instead). Typically this is the name (or names) of the database – this is server-side sorting, so what you pass depends on what your server expects to receive. width: The width of the column, in pixels. align: The alignment of the column. sortable: Specifies if the data in the grid can be sorted on this column; if false, clicking on the header has no effect. |
pager | Defines that we want to use a pager bar to navigate through the records. This must be a valid HTML element; in our example, we gave the div the id of “pager”, but any name is acceptable. Note that the Navigation layer (the “pager” div) can be positioned anywhere you want, determined by your HTML; in our example, we specified that the pager will appear after the Body layer. |
rowNum | Sets how many records we want to view in the grid. This parameter is passed to the URL for use by the server routine retrieving the data |
rowList | An array to construct a select box element in the pager in which we can change the number of the visible rows. When changed during the execution, this parameter replaces the rowNum parameter that is passed to the URL |
sortname | Sets the initial sorting column. Can be a name or number. This parameter is added to the URL for use by the server routine |
viewrecords | Defines whether we want to display the number of total records from the query in the pager bar |
caption | Sets the caption for the grid. If this parameter is not set the Caption layer will be not visible |
After setting up a script for creating JqGrid next we are going to Save and Run the application to have the first look at grid how it looks.
Snapshot of JqGrid
Adding Pager
Now above grid, we can see that we can see only 10 rows but we cannot see pager to this grid right let’s enable paging to this grid such that we can display large sets of data in it.
- Adding paging element <div> with id pager.
After adding pager element to view next step we need to add to more options to JqGrid.
- pager: jQuery('#pager'),
- rowList: [10, 20, 30, 40],
Code Snippet
- <script>
- $(function () {
- debugger;
- $("#Demogrid").jqGrid
- ({
- url: "/Demo/GetCustomers",
- datatype: 'json',
- mtype: 'Get',
-
- colNames: ['CustomerID', 'CompanyName', 'ContactName', 'ContactTitle', 'City', 'PostalCode', 'Country', 'Phone'],
-
- colModel: [
- { name: "CustomerID" },
- { name: "CompanyName" },
- { name: "ContactName" },
- { name: "ContactTitle" },
- { name: "City" },
- { name: "PostalCode" },
- { name: "Country" },
- { name: "Phone" }
- ],
- height: '100%',
- viewrecords: true,
- caption: 'JQgrid DEMO',
- emptyrecords: 'No records',
- rowNum: 10,
-
- pager: jQuery('#pager'),
- rowList: [10, 20, 30, 40],
-
- jsonReader:
- {
- root: "rows",
- page: "page",
- total: "total",
- records: "records",
- repeatitems: false,
- Id: "0"
- },
- autowidth: true,
- });
- });
- </script>
Snapshot of JqGrid
Debugging view after I change paging dropdown from 10 to 20.
Debugging view
Snapshot of JqGrid
After adding paging next we need to add icons for creating a new customer, editing customer, delete customer and also we need to search for this grid.
Adding edit, create, delete and search icons to grid pager
In this part we are going to add create, edit delete and search icons to the pager of the grid, for doing this we need to unable just few options on the grid.
These options are easy to set because they understand only Boolean value either true or false.
If we want to show only add icon then just make {add: true} and to hide it just make {add: false}.
- .navGrid('#pager',
- {
- edit: true,
- add: true,
- del: true,
- search: true,
- refresh: true,
- closeAfterSearch: true
- }
Code Snippet
- <script>
- $(function () {
- debugger;
- $("#Demogrid").jqGrid
- ({
- url: "/Demo/GetCustomers",
- datatype: 'json',
- mtype: 'Get',
-
- colNames: ['CustomerID', 'CompanyName', 'ContactName', 'ContactTitle', 'City', 'PostalCode', 'Country', 'Phone'],
-
- colModel: [
- { name: "CustomerID" },
- { name: "CompanyName" },
- { name: "ContactName" },
- { name: "ContactTitle" },
- { name: "City" },
- { name: "PostalCode" },
- { name: "Country" },
- { name: "Phone" }
- ],
- height: '100%',
- viewrecords: true,
- caption: 'JQgrid DEMO',
- emptyrecords: 'No records',
- rowNum: 10,
-
- pager: jQuery('#pager'),
- rowList: [10, 20, 30, 40],
-
- jsonReader:
- {
- root: "rows",
- page: "page",
- total: "total",
- records: "records",
- repeatitems: false,
- Id: "0"
- },
- autowidth: true,
- }).navGrid('#pager',
- {
- edit: true,
- add: true,
- del: true,
- search: true,
- refresh: true,
- closeAfterSearch: true
- });
- });
- </script>
Snapshot of JqGrid
After completing with adding icons now let’s work on how to add a new customer with JqGrid.
Adding new Customer
For adding new customer first we need to add action method which will handle create new customer request.
For doing that we are going to add new Action method with name “CreateCustomer” which will take Customer Model as an input parameter.
In this method we are first going on to validate data which we are going to receive from Ajax request if it is valid then we are going to save that data into the database with help of entity framework and finally, we are going return response to Ajax method. And if data is not valid then we going to read ModelState for errors and that error will be sent as a response to Ajax method.
Code Snippet
- [HttpPost]
- public JsonResult CreateCustomer([Bind(Exclude = "CustomerID")] Customers customers)
- {
- StringBuilder msg = new StringBuilder();
- try
- {
- if (ModelState.IsValid)
- {
- using (DatabaseContext db = new DatabaseContext())
- {
- db.Customers.Add(customers);
- db.SaveChanges();
- return Json("Saved Successfully", JsonRequestBehavior.AllowGet);
- }
- }
- else
- {
- var errorList = (from item in ModelState
- where item.Value.Errors.Any()
- select item.Value.Errors[0].ErrorMessage).ToList();
-
- return Json(errorList, JsonRequestBehavior.AllowGet);
- }
- }
- catch (Exception ex)
- {
- var errormessage = "Error occured: " + ex.Message;
- return Json(errormessage, JsonRequestBehavior.AllowGet);
- }
-
- }
After adding new action method which will handle post request next we need to add options to jqGrid which will post this request with CreateCustomer action method.
Code Snippet of JqGrid for creating new customer
- {
-
- zIndex: 100,
- url: "/Demo/CreateCustomer",
- closeOnEscape: true,
- closeAfterAdd: true,
- afterComplete: function (response) {
- if (response.responseJSON)
- {
- if (response.responseJSON == "Saved Successfully") {
- alert("Saved Successfully");
- }
- else {
- var message = "";
- for (var i = 0; i < response.responseJSON.length; i++) {
- message += response.responseJSON[i];
- message += "\n";
- }
- }
-
- }
- }
- }
After adding this options we are not going to see create customer popup for creating a new customer for doing that we need to add {editable: true} to each colModel property.
Code Snippet of adding editable: true to colModel property
- colModel:
- [
-
- { name: "CustomerID", editable: true },
- {
- name: "CompanyName", editable: true
- },
- {
- name: 'ContactName', editable: true
- },
- {
- name: "ContactTitle", editable: true
- },
- {
- name: "City", editable: true
- },
- {
- name: "PostalCode", editable: true
- },
- {
- name: "Country", editable: true
- },
- {
- name: "Phone", editable: true
- }
- ],
After setting editable options as true that columns are only going to be visible in add record popup.
Snapshot of JqGrid
But we have not added any validation to this fields till now.
Let’s add Validation to this fields.
Adding Validation (Required)
The first thing we need to add is to make all fields mandatory.
For doing this we need to add an editrules option to colModel.
editrules: {required: true}
Note: - editrules
This option adds additional properties to the editable element and should be used in colModel. Mostly it is used to validate the user input before submitting the value(s) to the server.
Referenced from - http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules
- colModel: [
- {
- name: "CustomerID", editable: true
- },
- {
- name: "CompanyName", editable: true, editrules: { required: true }
- },
- {
- name: 'ContactName', editable: true, editrules: { required: true }
- },
- {
- name: "ContactTitle", editable: true, editrules: { required: true }
- },
- {
- name: "City", editable: true, editrules: { required: true }
- },
- {
- name: "PostalCode", editable: true, editrules: { required: true }
- },
- {
- name: "Country", editable: true, editrules: { required: true }
- },
- {
- name: "Phone", editable: true, editrules: { required: true }
- }
- ],
Snapshot of JqGrid
After making all fields Mandatory next we need some validation such as a textbox should only accept integer value as input right for doing that we just need to add another option to that column.
Code Snippet
- {
- name: "PostalCode", editable: true, editrules: {required: true, number: true}
- }
Referenced from - http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules
Below is the list of available options:
Option | Type | Description |
edithidden | boolean | This option is valid only in form editing module. By default, the hidden fields are not editable. If the field is hidden in the grid and edithidden is set to true, the field can be edited when add or edit methods are called. |
required | boolean | (true or false) if set to true, the value will be checked and if empty, an error message will be displayed. |
number | boolean | (true or false) if set to true, the value will be checked and if this is not a number, an error message will be displayed. |
integer | boolean | (true or false) if set to true, the value will be checked and if this is not an integer, an error message will be displayed. |
minValue | number(integer) | if set, the value will be checked and if the value is less than this, an error message will be displayed. |
maxValue | number(integer) | if set, the value will be checked and if the value is more than this, an error message will be displayed. |
email | boolean | if set to true, the value will be checked and if this is not valid e-mail, an error message will be displayed |
url | boolean | if set to true, the value will be checked and if this is not valid url, an error message will be displayed |
date | boolean | if set to true a value from datefmt option is get (if not set ISO date is used) and the value will be checked and if this is not a valid date, an error message will be displayed |
time | boolean | if set to true, the value will be checked and if this is not a valid time, an error message will be displayed. Currently, we support only hh: mm format and optional am/pm at the end |
custom | boolean | if set to true allow the definition of the custom checking rules via a custom function. See below |
custom_func | function | this function should be used when a custom option is set to true. Parameters passed to this function are the value, which should be checked and the name - the property from colModel. The function should return an array with the following parameters: first parameter - true or false. The value of true means that the checking is successful false otherwise; the second parameter has sense only if the first value is false and represent the error message which will be displayed to the user. Typically this can look like this [false,”Please enter valid value”] |
After having a look at validation next we are finally going to create a new customer.
After posting data below is a snapshot of values populated in the model.
Snapshot of JqGrid
After completing with add new customer next we are going to Edit Customer.
Edit/Update Customer details
For editing records first, we need to add action method that will handle edit request.
In below code snippet we take customer model as input, after that we are going to validate Model and update values in the database.
If we fail to update then we are going to show the alert message.
Code Snippet
- public string EditCustomer(Customers customers)
- {
- string msg;
- try
- {
- if (ModelState.IsValid)
- {
- using (DatabaseContext db = new DatabaseContext())
- {
- db.Entry(customers).State = EntityState.Modified;
- db.SaveChanges();
- msg = "Saved Successfully";
- }
- }
- else
- {
- msg = "Some Validation ";
- }
- }
- catch (Exception ex)
- {
- msg = "Error occured:" + ex.Message;
- }
- return msg;
- }
Code Snippet
To enable edit/update option we need to add this piece of code to JqGrid.
- {
-
- zIndex: 100,
- url: '/Demo/EditCustomer',
- closeOnEscape: true,
- closeAfterEdit: true,
- recreateForm: true,
- afterComplete: function (response)
- {
- if (response.responseText)
- {
- alert(response.responseText);
- }
- }
- },
For updating and deleting data we need unique ID.
In jqGrid we can mark unique id by setting Key: true.
Code Snippet
- colModel: [
- {
- name: 'CustomerID',
- editable: true,
- key: true,
- hidden: true
- },
To edit record first we need to select a row then we need to click on Edit Icon.
After selecting a row and clicking on edit icon a popup will show with a record which you have chosen for editing.
In that, we are going to change phone number and click on submit button to update record, for updating data it is going to call EditCustomer Action Method.
Below is debugging view while update Customer data.
Debugging view
Output after updating data
After completing with edit customer next we are going to delete the record.
Delete Customer
For deleting records first we need to add action method that will handle delete request.
Below is code snippet which will handle delete request which takes Id (CustomerID) as input.
- public string DeleteCustomer(int Id)
- {
- using (DatabaseContext db = new DatabaseContext())
- {
- Customers customer = db.Customers.Find(Id);
- db.Customers.Remove(customer);
- db.SaveChanges();
- return "Deleted successfully";
- }
- }
To enable delete option we need to add this piece of code to JqGrid.
- {
-
- zIndex: 100,
- url: "/Demo/DeleteCustomer",
- closeOnEscape: true,
- closeAfterDelete: true,
- recreateForm: true,
- msg: "Are you sure you want to delete this Customer?",
- afterComplete: function (response) {
- if (response.responseText) {
- alert(response.responseText);
- }
- }
- }
In a similar way delete record first we need to select a row then we need to click on Delete Icon.
Delete confirmation message
If clicking on delete button it will call DeleteCustomer Action Method. For deleting we required unique id which is CustomerID which get populated as we click on delete button because we have set CustomerID column as Key in JqGrid.
Debugging view
Acknowledgement after deleting record
Finally most of the operation we have completed but still, one operation is pending is a search option.
Search Customer
To enable search first thing we need to do is enable search on the pager.
For doing that, we need to enable {search: true} in the pager.
Debugging view
- .navGrid('#pager',
- {
- edit: true,
- add: true,
- del: true,
- search: true,
- refresh: true,
- closeAfterSearch: true
- },
After that, you enable this option you can see search icon in grid footer.
But one issue here is that when you click on edit search it shows all columns names in the first dropdown list.
But we want to search on particular columns right for doing that we need to set {search} option to every column if we want to enable search for that column then set {search: true} and to disable search then set {search: false}.
We are going enable search for only 2 columns [CompanyName, ContactName]
Code Snippet
- colModel: [
- {
- name: 'CustomerID',
- editable: true,
- key: true,
- hidden: true,
- search: false
- },
- {
- name: "CompanyName", editable: true, editrules: { required: true }, search: true
- },
- {
- name: 'ContactName', editable: true, editrules: { required: true }, search: true
- },
- {
- name: "ContactTitle", editable: true, editrules: { required: true }, search: false
- },
- {
- name: "City", editable: true, editrules: { required: true }, search: false
- },
- {
- name: "PostalCode", editable: true, editrules: { required: true, number: true }, search: false
- },
- {
- name: "Country", editable: true, editrules: { required: true }, search: false
- },
- {
- name: "Phone", editable: true, editrules: { required: true }, search: false
- }
- ],
Next we are going to search record by CompanyName.
When we search, then are going to call GetCustomers Action Method.
In GetCustomers Action Method there is searchString parameter which gets populated with data what we search.
Debugging GetCustomers Action Method
Finally, let’s see complete code of Index View.
Complete Code Snippet of Index View
- @{
- Layout = null;
- }
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
- <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
-
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/jquery-ui-1.10.0.js"></script>
- <script src="~/Scripts/i18n/grid.locale-en.js"></script>
- <script src="~/Scripts/jquery.jqGrid.min.js"></script>
-
- <script>
- $(function ()
- {
- $("#Demogrid").jqGrid
- ({
- url: "/Demo/GetCustomers",
- datatype: 'json',
- mtype: 'Get',
-
- colNames: ['CustomerID', 'CompanyName', 'ContactName', 'ContactTitle', 'City', 'PostalCode', 'Country', 'Phone'],
-
- colModel: [
- {
- name: 'CustomerID',
- editable: true,
- key: true,
- hidden: true,
- search: false
- },
- {
- name: "CompanyName", editable: true, editrules: { required: true }, search: true
- },
- {
- name: 'ContactName', editable: true, editrules: { required: true }, search: true
- },
- {
- name: "ContactTitle", editable: true, editrules: { required: true }, search: false
- },
- {
- name: "City", editable: true, editrules: { required: true }, search: false
- },
- {
- name: "PostalCode", editable: true, editrules: { required: true, number: true }, search: false
- },
- {
- name: "Country", editable: true, editrules: { required: true }, search: false
- },
- {
- name: "Phone", editable: true, editrules: { required: true }, search: false
- }
- ],
- height: '100%',
- viewrecords: true,
- caption: 'JQgrid DEMO',
- emptyrecords: 'No records',
- rowNum: 10,
-
- pager: jQuery('#pager'),
- rowList: [10, 20, 30, 40],
-
- jsonReader:
- {
- root: "rows",
- page: "page",
- total: "total",
- records: "records",
- repeatitems: false,
- Id: "0"
- },
- autowidth: true
- }).navGrid('#pager',
- {
- edit: true,
- add: true,
- del: true,
- search: true,
- refresh: true,
- closeAfterSearch: true
- },
- {
-
- zIndex: 100,
- url: '/Demo/EditCustomer',
- closeOnEscape: true,
- closeAfterEdit: true,
- recreateForm: true,
- afterComplete: function (response)
- {
- if (response.responseText)
- {
- alert(response.responseText);
- }
- }
- },
- {
-
- zIndex: 100,
- url: "/Demo/CreateCustomer",
- closeOnEscape: true,
- closeAfterAdd: true,
- afterComplete: function (response) {
- if (response.responseJSON)
- {
- if (response.responseJSON == "Saved Successfully") {
- alert("Saved Successfully");
- }
- else {
- var message = "";
- for (var i = 0; i < response.responseJSON.length; i++) {
- message += response.responseJSON[i];
- message += "\n";
- }
- }
-
- }
- }
- },
- {
-
- zIndex: 100,
- url: "/Demo/DeleteCustomer",
- closeOnEscape: true,
- closeAfterDelete: true,
- recreateForm: true,
- msg: "Are you sure you want to delete this Customer?",
- afterComplete: function (response) {
- if (response.responseText) {
- alert(response.responseText);
- }
- }
- }
-
- );
- });
- </script>
- </head>
- <body>
- <div>
- <table id="Demogrid"></table>
- <div id="pager"></div>
- </div>
- </body>
- </html>
Wow, finally we have completed how to using JqGrid with ASP.NET MVC.
Source code and database script is available for download.