I hope we all know how to create a new project in Visual Studio while we start to develp a ASP.NET MVC application, so I am not going to explain all those steps. Lets dive into code directly for Model, Controller & View.

You can download complete source code from : https://www.dropbox.com/s/hymjguzu40nz0nm/Savex.zip?dl=0

Here, I have created a Customer class model & a CustomerController. Let's make is simple without any dataanotations/validations. Of course that can be added later on.

//Customer class (Model):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Savex.Models
    public class Customer
        public int CustomerId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Mobile { get; set; }
        public string Email { get; set; }

Customer Controller : 

    public class CustomerController : Controller
        private SavexContext db = new SavexContext();


public JsonResult GetCustomers(string sidx, string sort, int page, int rows)
            SavexContext db = new SavexContext();
            sort = (sort == null) ? "" : sort;
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            var CustomerList = db.Customers.Select(
                t=> new
            int totalRecords = CustomerList.Count();
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
            if(sort.ToUpper() == "DESC")
                CustomerList = CustomerList.OrderByDescending(t => t.FirstName);
                CustomerList = CustomerList.Skip(pageIndex * pageSize).Take(pageSize);
                CustomerList = CustomerList.OrderBy(t => t.FirstName);
                CustomerList = CustomerList.Skip(pageIndex * pageSize).Take(pageSize);
            var jsonData = new
                total = totalPages,
                records = totalRecords,
                rows = CustomerList
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        protected override void Dispose(bool disposing)
            if (disposing)

In above code of controller, we have initialezed the dbcontext object to interact with CRM which in this case is Entity Framework. The "GetCustomers" method returns JsonResult, accepts parameters like start index, sort order, page size & total rows.

Now, lets add a Script.js file under Scripts folder in our project and add the following JS method in it.

$(function () {
        url: "/Customer/GetCustomers",
        datatype: 'json',
        mtype: 'Get',
        colNames: ['CustomerId''First Name''Last Name''Mobile''Email'],
        colModel: [
            { key: true, hidden: true, name: 'CustomerId', index: 'CustomerId'},
            { key: false, name: 'FirstName', index: 'FirstName', editable: true },
            { key: false, name: 'LastName', index: 'LastName', editable: true },
            { key: false, name: 'Mobile', index: 'Mobile', editable: true },
            { key: false, name: 'Email', index: 'Email', editable: true }],
        pager: jQuery('#jqControls'),
        rowNum: 10,
        rowList: [51020304050],
        height: '100%',
        viewrecords: true,
        caption: 'Customers',
        emptyrecords: 'No Records to Display',
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            Id: "0"
        autowidth: true,
        multiselect: false
    }).navGrid('#jqControls', { edit: true, add: true, del: true, search: false

, refresh: true },         {             zIndex: 100,             url: '/Customer/Edit',             closeOnEscape: true,             closeAfterEdit: true,             recreateForm: true,             //afterComplete: function (response) {             //    if (response.responseText) {             //        alert(response.responseText);             //    }             //}         },         {             zIndex: 100,             url: "/Customer/Create",             closeOnEscape: true,             closeAfterAdd: true,             //afterComplete: function (response) {             //    if (response.responseText) {             //        alert(response.responseText);             //    }             //}         },         {             zIndex: 100,             url: "/Customer/Delete",             closeOnEscape: true,             closeAfterDelete: true,             recreateForm: true,             msg: "Are you sure to delete ? ",             //afterComplete: function (response) {             //    if (response.responseText) {             //        alert(response.responseText);             //    }             //}         }); });  

Here, we added a jquery method. Make sure you have installed JQery Grid from either Manage Package or from Package Maanger Console. You can see "Jquery.JqGrid.js" inside your Scripts folder.

In this method, we are refering to url which reads /Customer/GetCustomers where "Customer" : is the controller name and "GetCustomers" : is the action. The type of method is GET. Next is column names which we want to display & colModel tells from which Entity Object the columns are refered. Note I have marked "CustomerId" field as hidden, as its my Identty Column but you can change it as needed.

For paging, we have a parameter which is page: jQuery("#jqControls"). Similary, we have other parameters which are quite easy to understand from code.

Finally, we have our View Index.cshtml as follows:

@model IEnumerable<Savex.Models.Customer>
    ViewBag.Title = "Index";
    @Html.ActionLink("Create New""Create")
    <table id="jqGrid">table>
    <div id="jqControls">div>
@section scripts{
    <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
    <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
    <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 src="~/Scripts/Script.js">script>

Please note that we have defined a table with id "jqGrid" and a div "jqControls" which we are calling inside our jquery method.

Note that we have also implemented requests for CRUD operations in our jquery method. Following are our jquery requests:-

url: '/Customer/Edit'
url: "/Customer/Create"
url: "/Customer/Delete"

In order to make it working we have to complete our Customer Controller. Lets finish it up.

// GET: Customer/Create
        public async Task<ActionResult> Create(
[Bind(Include = "FirstName,LastName,Mobile,Email")] Customer customer)         {             if (ModelState.IsValid)             {                 db.Customers.Add(customer);                 await db.SaveChangesAsync();                 return RedirectToAction("Index");             }             return View(customer);         }         // GET: Customer/Edit/5         public async Task<ActionResult> Edit(
[Bind(Include = "CustomerId,FirstName,LastName,Mobile,Email")] Customer customer)         {             try             {                 if (ModelState.IsValid)                 {                     db.Entry(customer).State = EntityState.Modified;                     await db.SaveChangesAsync();                     return RedirectToAction("Index");                 }             }             catch (DataException)             {                 ModelState.AddModelError("""Unable to save, please try later.");             }             return View(customer);         }         // GET: Customer/Delete/5         public async Task<ActionResult> Delete(int? id)         {             //if(saveChangesError.GetValueOrDefault())             //{             //    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);             //}             if (id == null)             {                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);             }             Customer customer = await db.Customers.FindAsync(id);             if (customer == null)             {                 return HttpNotFound();             }             db.Customers.Remove(customer);             await db.SaveChangesAsync();             return View(customer);         }


Note that we are using async, await in our controller in order to handle requests and serve. 

You can download complete source code from : https://www.dropbox.com/s/hymjguzu40nz0nm/Savex.zip?dl=0


blog comments powered by Disqus