We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Friday, August 11, 2017

CRUD operation using Code first approach, web api, Repository pattern, Unit of work and jqGrid in mvc

Today, In this article, I will explain that how to Perform CRUD operation in MVC  using Code First Approach, Web Api, Repository  pattern, Unit of work and jqgrid. In this article, I will create  different-different layers such as Data access Layer, Business Layer, Service Layer and Presentation Layer also we will check some validation in jqgrid. Now  Let us see step by step.
Step 1 :

We will create a  table in database.
Here set "EmployeeNo" as a primary key and set Identity yes.


Step 2
Now we will add projects using class library like DataAccessLayer, BusinessLayer ,ServiceLayer,PersentationLayer


So first we will Create a MVC empty project and then we will add project one by one so first we will add DataAccessLayer.
So for this, Right click of project solution and got to the "Add" option and select "new project" option and select Class library file and Give the name as CRUD.DataLayer (This is my example name you can give any name).


And select Ok
Similarly we have to add 3 more project .
Right click of project solution and got to the "Add" option and select "new project" option and select Class library file and Give the name as CRUD.Bussiness(This is my example name you can give any name).

, Right click of project solution and got to the "Add" option and select "new project" option and select Class library file and Give the name as CRUD.Service(This is my example name you can give any name).
, Right click of project solution and got to the "Add" option and select "new project" option and select Class library file and Give the name as CRUD.Presentation (This is my example name you can give any name).

Okay, Now project adding has completed so next just build one by one add DLL.
So first build DataAccessLayer project and build and DLL of DataAccessLayer in BussinessLayer
for this, Right click of the project and select add option and select Reference option


And select CRUD.DataLayer.dll

So similarly we have to add DLL of business in Service Layer
So DLL adding are completed
Step 3 
We will go first Data Access Layer and add model classes but here we will use code first approach using existing data
So for this, First we will add a folder like "Entity".
After that go right click of Entity folder select add option and select new item
and then select data in left panel and select ADO.Net Entity data model


Click add button
after that we will select Code First From database


Go next and Give the connection and select table of database

After that again we will create a folder for this my folder name is Implementation
and this folder add two class
1. DataAccess.cs
2. UnitOfWork.cs

Write code in  DataAccess.cs
using CRUD.DataLayer.Entities;
using CRUD.DataLayer.Interfaces;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace CRUD.DataLayer.Implementation
{
    public class DataAccess<TEntity> : IDataAccess<TEntity> where TEntity : class
    {
        /// <summary>
        /// The context
        /// </summary>
        internal MyModel context;

        /// <summary>
        /// The database set
        /// </summary>
        internal DbSet<TEntity> dbSet;

        /// <summary>
        /// Initializes the new instance of MyModel Model
        /// </summary>
        /// <param name="context">context object</param>
        public DataAccess(MyModel context)
        {
            this.context = context;
            this.dbSet = context.Set<TEntity>();
        }

        /// <summary>
        /// Gets all data
        /// </summary>
        /// <returns>collection of specified class.</returns>
        public virtual IEnumerable<TEntity> Get()
        {
            IQueryable<TEntity> query = this.dbSet;
            return query.ToList();
        }

        /// <summary>
        /// Gets the by identifier.
        /// </summary>
        /// <param name ="id"> The identifier.</param>
        /// <returns> object </returns>
        public virtual TEntity GetByID(object id)
        {
            return this.dbSet.Find(id);
        }

        /// <summary>
        /// Insert data
        /// </summary>
        /// <param name="entity">object for insertion.</param>
        public virtual void Insert(TEntity entity)
        {
            this.dbSet.Add(entity);
        }

        /// <summary>
        ///  Delete data by id
        /// </summary>
        /// <param name="id">id</param>
        public virtual void Delete(object id)
        {
            TEntity entityToDelete = this.dbSet.Find(id);
            this.Delete(entityToDelete);
        }

        /// <summary>
        /// Delete data
        /// </summary>
        /// <param name ="entityToDelete">entity To Delete.</param>
        public virtual void Delete(TEntity entityToDelete)
        {
            if (this.context.Entry(entityToDelete).State == System.Data.Entity.EntityState.Detached)
            {
                this.dbSet.Attach(entityToDelete);
            }

            this.dbSet.Remove(entityToDelete);
        }

        /// <summary>
        /// Attach data.
        /// </summary>
        /// <param name="entityToUpdate">entity To Update.</param>
        public virtual void Attach(TEntity entityToUpdate)
        {
            this.dbSet.Attach(entityToUpdate);
            this.context.Entry(entityToUpdate).State = System.Data.Entity.EntityState.Modified;
        }
    }
}

Write code in  UnitOfWork.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CRUD.DataLayer.Entities;

namespace CRUD.DataLayer.Implementation
{

    /// <summary>
    /// The UnitOfWork class designed for binding classes to generic class DataAccess. This class is the conversion or binding class
    /// </summary>
    /// <seealso cref="System.IDisposable" />
    public class UnitOfWork : IDisposable
    {
        /// <summary>
        /// Stores the string error message
        /// </summary>
        private string errorMessage = string.Empty;

        /// <summary>
        /// Defines condition for disposing object
        /// </summary>
        private bool disposed = false;

        private DataAccess<EmployeeInfo> employeeInfoRepository;

        /// <summary>
        /// Initializes a new instance of the MyModel class
        /// </summary>
        private MyModel objMyModel = new MyModel();


        /// <summary>
        /// Gets the get employee repository.
        /// </summary>
        /// <value>
        /// The get employee repository.
        /// </value>
        public DataAccess<EmployeeInfo> GetEmployeeRepository
        {
            get
            {
                if (this.employeeInfoRepository == null)
                {
                    this.employeeInfoRepository = new DataAccess<EmployeeInfo>(this.objMyModel);
                }

                return this.employeeInfoRepository;
            }
        }


        /// <summary>
        /// This Method will commit the changes to database for the permanent save
        /// </summary>
        /// <returns>
        /// affected rows
        /// </returns>
        public int Save()
        {
            return this.objMyModel.SaveChanges();
        }
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }


        /// <summary>
        /// This method will dispose the context class object after the uses of that object
        /// </summary>
        /// <param name="disposing">parameter true or false for disposing database object</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    this.objMyModel.Dispose();
                }
            }

            this.disposed = true;
        }
    }
}


Now we have completed data access part.
So now we will go
Step 4
Now we go Business Layer
Here we will create two folder
1. Implementation
2. Interfaces

So will add interface class like IEmployee.cs and declare methods
using System.Collections.Generic;
using CRUD.DataLayer.Entities;

namespace CRUD.BusinessLayer.Interfaces
{
    public interface IEmployee
    {
        IEnumerable<EmployeeInfo> EmployeeGet();
        string EmployeeInsert(EmployeeInfo emp);
        string EmployeeUpdate(EmployeeInfo emp);
        string EmployeeDelete(int id);
    }
}

Now will add class like Employee.cs in Implementation folder
using CRUD.BusinessLayer.Interfaces;
using System.Collections.Generic;
using System.Linq;
using CRUD.DataLayer.Entities;
using CRUD.DataLayer.Implementation;


namespace CRUD.BusinessLayer.Implementation
{
    public class Employee : IEmployee
    {
        private UnitOfWork unitOfWork = new UnitOfWork();

        private List<EmployeeInfo> lstEmp = new List<EmployeeInfo>();
        private EmployeeInfo objEmp = new EmployeeInfo();
        public IEnumerable<EmployeeInfo> EmployeeGet()
        {
            lstEmp = unitOfWork.GetEmployeeRepository.Get().ToList();

            return lstEmp;
        }

        public string EmployeeUpdate(EmployeeInfo emp)
        {

            objEmp = unitOfWork.GetEmployeeRepository.GetByID(emp.EmployeeNo);

            if(objEmp !=null)
            {
                objEmp.FirstName = emp.FirstName;
                objEmp.LastName = emp.LastName;
                objEmp.Address = emp.Address;
                objEmp.MobileNo = emp.MobileNo;
                objEmp.PostelCode = emp.PostelCode;
                objEmp.EmailId = emp.EmailId;
            }
            this.unitOfWork.GetEmployeeRepository.Attach(objEmp);
            int result = this.unitOfWork.Save();

            if(result > 0)
            {
                return "Sucessfully updated of employee records";
            }
            else
            {
                return "Updation faild";
            }
        }

        public string EmployeeDelete(int id)
        {
            var objEmp = this.unitOfWork.GetEmployeeRepository.GetByID(id);
            this.unitOfWork.GetEmployeeRepository.Delete(objEmp);
            int deleteData = this.unitOfWork.Save();
            if(deleteData > 0)
            {
                return "Successfully deleted of employee records";
            }
            else
            {
                return "Deletion faild";
            }
        }

        public string EmployeeInsert(EmployeeInfo emp)
        {
         this.unitOfWork.GetEmployeeRepository.Insert(emp);
            int inserData =this.unitOfWork.Save();

            if(inserData > 0)
            {
                return "Successfully Inserted of employee records";
            }
            else
            {
                return "Insertion faild";
            }
        }
    }
}

So now we have completed business layer part
next we will go service layer

Step 5

Now we have to add API Controller  in Service layer .
Right click of controller and add a api controller



Click add



And we write the code for all operation to perform CRUD Operation in EmplyeeAPI Controller
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using CRUD.DataLayer.Entities;
using CRUD.BusinessLayer.Implementation;
using CRUD.BusinessLayer.Interfaces;

namespace CRUD.ServiceLayer.Controllers
{
    [System.Web.Http.RoutePrefix("api/Employee")]
    public class EmployeeAPIController : ApiController
    {

        IEmployee objEmp = new Employee();

        [System.Web.Http.HttpGet]
        [System.Web.Http.Route("EmpDetails")]
        public IEnumerable<EmployeeInfo> GetEmployeeData()
        {
         

            IEnumerable<EmployeeInfo> empDetail = new List<EmployeeInfo>();
            try
            {
                empDetail = objEmp.EmployeeGet();
            }
            catch (ApplicationException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });
            }

            return empDetail;
        }


        [System.Web.Http.HttpPost]
        [System.Web.Http.Route("InsertEmpDetails")]
        public string InserEmployee(EmployeeInfo objEmpDetails)
        {
            string objEmployee;
            try
            {
                objEmployee = this.objEmp.EmployeeInsert(objEmpDetails);
            }
            catch (ApplicationException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });
            }

            return objEmployee;
        }

        [System.Web.Http.HttpPut]
        [System.Web.Http.Route("UpdateEmpDetails")]
        public string UpdateEmployee(EmployeeInfo objEmpDetails)
        {
            string objEmployee;
            try
            {
                objEmployee = this.objEmp.EmployeeUpdate(objEmpDetails);
            }
            catch (ApplicationException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });
            }

            return objEmployee;
        }
        [System.Web.Http.HttpDelete]
        [System.Web.Http.Route("DeleteEmpData/{id}")]
        public string DeleteEmployeeData(int id)
        {
            string objEmpDetails;
            try
            {
                objEmpDetails = this.objEmp.EmployeeDelete(id);
            }
            catch (ApplicationException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });
            }

            return objEmpDetails;
        }
    }
}


After that we will run the web api project the find some output


Okay we have completed also Service layer part so now we have to consume in mvc so for this we will go Presentation layer part I.e MVC Layer

Step 6
First we will add a controller
So for this, Go to controller folder and right click and add a empty controller



Now we have to consume we api service and finally we have to display records in view
so here will add a class in model folder and give a class name as example Rest Client. This is for common class for perform all CRUD operation

Here We need to url of our service layer

public const string ApiUri = "http://localhost:52133/";

And write the methods in RestClient Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace PersentationLayer.Models
{
    public class RestClient : IDisposable
    {
        /// <summary>
        /// The client
        /// </summary>
        private HttpClient client;
        public const string ApiUri = "http://localhost:52133/";
        /// <summary>
        /// Media type used for send data in API
        /// </summary>
        public const string MediaTypeJson = "application/json";

        /// <summary>
        /// Media type used for send data in API
        /// </summary>
        public const string MediaTypeXML = "application/XML";

        public const string RequestMsg = "Request has not been processed";
        public static string ReasonPhrase { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="RestClient"/> class.
        /// </summary>
        public RestClient()
        {
            this.client = new HttpClient();
            this.client.BaseAddress = new Uri(ApiUri);
            this.client.DefaultRequestHeaders.Accept.Clear();
            this.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeJson));
        }
        public async Task<List<U>> RunAsyncGetAll<T, U>(dynamic uri)
        {
            HttpResponseMessage response = await this.client.GetAsync(uri);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsAsync<List<U>>();
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                throw new ApplicationException(response.ReasonPhrase);
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)
            {
                throw new Exception(response.ReasonPhrase);
            }

            throw new Exception(RequestMsg);
        }

        public async Task<List<U>> RunAsyncGet<T, U>(dynamic uri, dynamic data)
        {
            HttpResponseMessage response = await this.client.GetAsync(uri + "/" + data);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsAsync<List<U>>();
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                throw new ApplicationException(response.ReasonPhrase);
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)
            {
                throw new Exception(response.ReasonPhrase);
            }

            throw new Exception(RequestMsg);
        }

        public async Task<U> RunAsyncPost<T, U>(string uri, T entity)
        {
            HttpResponseMessage response = client.PostAsJsonAsync(uri, entity).Result;
            ReasonPhrase = response.ReasonPhrase;
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsAsync<U>();
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                throw new ApplicationException(response.ReasonPhrase);
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)
            {
                throw new Exception(response.ReasonPhrase);
            }

            throw new Exception(RequestMsg);
        }

        public async Task<U> RunAsyncPut<T, U>(string uri, T entity)
        {
            HttpResponseMessage response = await this.client.PutAsJsonAsync(uri, entity);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsAsync<U>();
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                throw new ApplicationException(response.ReasonPhrase);
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)
            {
                throw new Exception(response.ReasonPhrase);
            }

            throw new Exception(RequestMsg);
        }

        public async Task<U> RunAsyncDelete<T, U>(string uri, dynamic id)
        {
            HttpResponseMessage response = await this.client.DeleteAsync(uri + "/" + id);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsAsync<U>();
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                throw new ApplicationException(response.ReasonPhrase);
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)
            {
                throw new Exception(response.ReasonPhrase);
            }

            throw new Exception(RequestMsg);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                //// dispose managed resources
                this.client.Dispose();
            }
            //// free native resources
        }
    }
}


Add one more class in model folder for declare all entities of employee
Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PersentationLayer.Models
{
    public class Employee
    {
            public int EmployeeNo { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }

            public string Address { get; set; }
            public string MobileNo { get; set; }
            public string PostelCode { get; set; }
            public string EmailId { get; set; }
        }
} 
After that we will write all code in Mvc controller class
using System;
using System.Web.Mvc;
using PersentationLayer.Models;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net;
using System.Web.Http;

namespace PersentationLayer.Controllers
{
    public class EmployeeController : Controller
    {

        private RestClient restClient = new RestClient();
        // GET: Employee
        public ActionResult EmployeeDetails()
        {
            return this.View();
        }
        public async Task<ActionResult> EmpInfoData()
        {
            try
            {

                return this.Json(await this.restClient.RunAsyncGetAll<Employee, Employee>("api/Employee/EmpDetails"), JsonRequestBehavior.AllowGet);
            }
            catch (ApplicationException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });

            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });
            }
        }

        public async Task<ActionResult> InsertEmployeeInfo(Employee objEmp)
        {
            try
            {
                return this.Json(await this.restClient.RunAsyncPost<Employee, string>("api/Employee/InsertEmpDetails", objEmp));
            }
            catch (ApplicationException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });
            }
        }
        public async Task<ActionResult> UpdateEmployeeInfo(Employee objEmp)
        {
            try
            {
                return this.Json(await this.restClient.RunAsyncPut<Employee, string>("api/Employee/UpdateEmpDetails", objEmp));
            }
            catch (ApplicationException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });
            }
        }


        public async Task<ActionResult> DeleteEmployeeInfo(int id)
        {
            try
            {
                return this.Json(await this.restClient.RunAsyncDelete<int, string>("api/Employee/DeleteEmpData", id));
            }
            catch (ApplicationException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });
            }
        }

    }
}

Now we will display all records in view but here we will use jqGrid for view the records so first we have to add jqrid library
so for this we will go ManageNew Get Package
and search jqGrid library and install.


now we will write code related jqgrid so for we will take a separate  java script file and give a name like EmpDetails.js and write code
/// <reference path="jqGrid/jquery.jqGrid.js" />

var EmployeeDetails = {

    GetEmpData: function () {
        $("#list").jqGrid({
            url: '/Employee/EmpInfoData',
            datatype: 'json',
            mtype: 'Get',
            colModel: [
                {
                    key: true, hidden: true, name: 'EmployeeNo', index: 'EmployeeNo', editable: true
                },

                          { key: false, name: 'FirstName', index: 'FirstName', width: 245, editable: true, editrules: { required: true }, },

                            { name: 'LastName', index: 'LastName', width: 245, editable: true, editrules: { required: true }, },
                               { name: 'Address', index: 'Address', width: 245, editable: true, editrules: { required: true }, },

                          {
                              name: 'MobileNo', index: 'MobileNo', width: 245, editable: true, editrules: { required: true }, editoptions: {
                                  maxlength: "10", dataInit: function (element) {
                                      $(element).keypress(function (e) {
                                          if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                                              alert("Accept only numeric value and only ten digits");
                                              return false;
                                          }
                                      });
                                  }
                              }
                          },

                          {
                              name: 'PostelCode', index: 'PostelCode', width: 145, editable: true, editrules: { required: true }, editoptions: {
                                  maxlength: "6", dataInit: function (element) {
                                      $(element).keypress(function (e) {

                                          if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {

                                              alert("Accept only numeric value and only six digits");
                                              return false;
                                          }
                                      });
                                  }
                              }
                          },
                            { name: 'EmailId', index: 'EmailId', width: 245, editable: true, editrules: { required: true }, }
            ],
            pager: jQuery('#pager'),
            rowNum: 10,
            loadonce: true,
            rowList: [10, 20, 30, 40],
            height: '100%',
            viewrecords: true,
            caption: 'Employee Details',
            emptyrecords: 'No records to display',
            jsonReader: {
                repeatitems: false,
                root: function (obj) { return obj; },
                page: "page",
                total: "total",
                records: "records",
                repeatitems: false,
                EmployeeNo: "0"
            },
            autowidth: true,
            multiselect: false
        }).navGrid('#pager', { add: false, edit: true, del: true, search: false, refresh: true },
       {
           // edit options
           zIndex: 1000,
           url: '/Employee/UpdateEmployeeInfo',
           closeOnEscape: true,
           closeAfterEdit: true,
           recreateForm: true,
           loadonce: true,
           align: 'center',
           afterComplete: function (response) {
               GetEmpData()
               if (response.responseText) {
                 
                   alert(response.responseText);
               }
           }
       }, {},
       {
           // delete options
           zIndex: 1000,
           url: '/Employee/DeleteEmployeeInfo',
           closeOnEscape: true,
           closeAfterdel: true,
           recreateForm: true,
           msg: "Are you sure you want to delete this task?",
           afterComplete: function (response) {
               if (response.responseText) {
                   $("#alert-Grid").html("<b>" + response.responseText + "</b>");
                   $("#alert-Grid").show();
                   $("#alert-Grid").delay(3000).fadeOut("slow");
               }
           }
       });
    },
    insertEmployeeDetails: function () {
    
        $("#btnSubmit").click(function () {
        
            $.ajax(
            {
                type: "POST", //HTTP POST Method 
                url: "/Employee/InsertEmployeeInfo", // Controller/View  
                data: { //Passing data 

                    FirstName: $("#txtFName").val(), //Reading text box values using Jquery  
                    LastName: $("#txtLName").val(),
                    Address: $("#txtAddress").val(),
                    MobileNo: $("#txtMobileNo").val(),
                    PostelCode: $("#txtPinCode").val(),
                    EmailId: $("#txtEmail").val()
                },
                success: function (data) {
                    alert(data);
                    $("##alert-danger").html("<b>" + data + "</b>");
                    $("##alert-danger").show();
                    $("##alert-danger").delay(10000).fadeOut("slow");
                },
                error: function (data) {
                    GetEmpData();
                    //var r = data.responseText;
                    //var errorMessage = r.Message;
                    $("##alert-danger").html("<b>" + data + "</b>");
                    $("##alert-danger").show();
                    $("##alert-danger").delay(10000).fadeOut("slow");
                }
            });
        });
    }
}





Now will design ui with Html in view

@{
    ViewBag.Title = "EmployeeDetails";
}


<link href="~/themes/jquery-ui-1.12.1.custom/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />


<script src="~/Scripts/jquery-1.9.1.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 src="~/Scripts/EmpDetails.js"></script>
<br />
<div class="row">
    <div class="col-xs-4 col-md-2"></div>
    <div class="col-xs-6 col-md-8" ng-hide="showHide">
        <div class="panel panel-default">
            <div class="panel-heading" style="background-color:#4B7082;color:white"><h4 align="center">Add New Employee Records</h4></div>
            <div class="panel-body">
                <div class="row">
                    <form class="form-inline" id="form1">
                    
                        <div class="col-md-5" style="padding-left:80px;">
                            <div class="form-inline">
                                <label for="" id="label">First Name</label>
                                <input type="text" class="form-control" required id="txtFName">
                            </div>
                            <br />
                            <div class="form-inline">
                                <label for="" id="label">Address</label>
                                <input type="text" class="form-control" required id="txtAddress">

                            </div>
                            <br />
                            <div class="form-inline">
                                <label for="" id="label">Pin Code</label>
                                <input type="text" class="form-control" required id="txtPinCode">

                            </div>
                        </div>
                        <div class="col-md-5"  style="padding-left:80px;">
                            <div class="form-inline">
                                <label for="" id="label">Last Name</label>
                                <input type="text" required id="txtLName" class="form-control">
                            </div>
                            <br />
                            <div class="form-inline">
                                <label for="" id="label">Mobile Number</label>
                                <input type="text" class="form-control" required id="txtMobileNo">

                            </div><br />
                            <div class="form-inline">
                                <label for="" id="label">Email Id</label>
                                <input type="text" class="form-control" required id="txtEmail">

                            </div>
                            <br />
                                    <input type="submit" class="btn btn-success"  id="btnSubmit" value="Submit" />
                             
                            </div>
                      
                  
                    </form>
                </div>

            </div>
        </div>
    </div>
    <div class="col-xs-6 col-md-2"></div>
</div>
<div class="row">
    <div class="col-md-10 col-md-offset-1">
        <div class="alert alert-danger" role="alert" id="alert-Grid"></div>
        <table align="center" id="list"></table>
        <div id="pager"></div>

    </div>
</div>

Now we will call the our jqgrid methods in view
so write this code in view page

<script type="text/javascript">
    $(function () {
        $("#alert-Grid").hide();
        EmployeeDetails.GetEmpData();
        EmployeeDetails.insertEmployeeDetails();

    });

        
</script>

 So we can see this is my finally view.


We will Insert, Update and delete our records
so for update records we will go update option


Here, It is working all related validation we can see mobile number should be numeric but try to give alphabetic then it will show error.

Note: You want to download full solution then go this link.
Thanks and happy coding.

No comments: