CRUD Operation Using Code First Approach, Web API, Repository Pattern, Unit Of Work, And jqGrid In MVC

In this article I will explain how to perform CRUD operations in MVC using Code First Approach, Web API, Repository pattern, Unit of work, and jqGrid. I will also create several different layers, including Data Access Layer, Business Layer, Service Layer, and Presentation Layer. Also, we will check some validation in jqgrid. Now, lets get started.

Step 1

We will create a table in the database.

Code First Approach
Here, set "EmployeeNo" as a primary key and set Identity to "Yes".

Code First Approach

Step 2

Now, we will add projects using class library, like DataAccessLayer, BusinessLayer, ServiceLayer, and PersentationLayer.

Code First Approach
First, we will create an MVC empty project and then we will add projects one by one. We will add tje DataAccessLayer first.

For this, right click on project solution and go to Add >> New Project.

Select Class library file and give it name such as CRUD.DataLayer (This is my example name, you can give any name).

Code First Approach 

Click OK.

Similarly, we have to add 3 more projects.
  • Right click on project solution and go to Add >> New Project. Select Class library file and give it name as CRUD.Bussiness .

  • Right click on project solution and go to Add >> New Project. Select Class library file and give it name as CRUD.Service.

  • Right click on project solution and go to Add >> New Project. Select Class library file and give it name as CRUD.Presentation.

Okay! Now let's add the DLL files.

First we build a DataAccessLayer project and add the DLL file DataAccessLayer in the BussinessLayer. For this, right click on the project and select Add >> Reference. Select CRUD.DataLayer.dll.

Code First Approach

Similarly, we have to add DLL file Business Layer in the Service Layer

Step 3 

We will go to the Data Access Layer and add model classes but here we will use the code first approach using existing data. So for this, we add a folder like "Entity." After that right click the Entity folder and select the add option and select new item and then select data in the left panel and finally select ADO.Net Entity data model.

Code First Approach

Click add button.

After that we will select Code First From database.

Code First Approach

Click next and give the connection and select the table of the database. 

After that again we will create a folder, my folder name is Implementation.

And this folder add two classes.

  1. DataAccess.cs
  2. UnitOfWork.cs

Write code in DataAccess.cs

  1. using CRUD.DataLayer.Entities;  
  2. using CRUD.DataLayer.Interfaces;  
  3. using System.Collections.Generic;  
  4. using System.Data.Entity;  
  5. using System.Linq;  
  6.   
  7. namespace CRUD.DataLayer.Implementation  
  8. {  
  9.     public class DataAccess<TEntity> : IDataAccess<TEntity> where TEntity : class  
  10.     {  
  11.         /// <summary>  
  12.         /// The context  
  13.         /// </summary>  
  14.         internal MyModel context;  
  15.   
  16.         /// <summary>  
  17.         /// The database set  
  18.         /// </summary>  
  19.         internal DbSet<TEntity> dbSet;  
  20.   
  21.         /// <summary>  
  22.         /// Initializes the new instance of MyModel Model  
  23.         /// </summary>  
  24.         /// <param name="context">context object</param>  
  25.         public DataAccess(MyModel context)  
  26.         {  
  27.             this.context = context;  
  28.             this.dbSet = context.Set<TEntity>();  
  29.         }  
  30.   
  31.         /// <summary>  
  32.         /// Gets all data  
  33.         /// </summary>  
  34.         /// <returns>collection of specified class.</returns>  
  35.         public virtual IEnumerable<TEntity> Get()  
  36.         {  
  37.             IQueryable<TEntity> query = this.dbSet;  
  38.             return query.ToList();  
  39.         }  
  40.   
  41.         /// <summary>  
  42.         /// Gets the by identifier.  
  43.         /// </summary>  
  44.         /// <param name ="id"> The identifier.</param>  
  45.         /// <returns> object </returns>  
  46.         public virtual TEntity GetByID(object id)  
  47.         {  
  48.             return this.dbSet.Find(id);  
  49.         }  
  50.   
  51.         /// <summary>  
  52.         /// Insert data  
  53.         /// </summary>  
  54.         /// <param name="entity">object for insertion.</param>  
  55.         public virtual void Insert(TEntity entity)  
  56.         {  
  57.             this.dbSet.Add(entity);  
  58.         }  
  59.   
  60.         /// <summary>  
  61.         ///  Delete data by id  
  62.         /// </summary>  
  63.         /// <param name="id">id</param>  
  64.         public virtual void Delete(object id)  
  65.         {  
  66.             TEntity entityToDelete = this.dbSet.Find(id);  
  67.             this.Delete(entityToDelete);  
  68.         }  
  69.   
  70.         /// <summary>  
  71.         /// Delete data  
  72.         /// </summary>  
  73.         /// <param name ="entityToDelete">entity To Delete.</param>  
  74.         public virtual void Delete(TEntity entityToDelete)  
  75.         {  
  76.             if (this.context.Entry(entityToDelete).State == System.Data.Entity.EntityState.Detached)  
  77.             {  
  78.                 this.dbSet.Attach(entityToDelete);  
  79.             }  
  80.   
  81.             this.dbSet.Remove(entityToDelete);  
  82.         }  
  83.   
  84.         /// <summary>  
  85.         /// Attach data.  
  86.         /// </summary>  
  87.         /// <param name="entityToUpdate">entity To Update.</param>  
  88.         public virtual void Attach(TEntity entityToUpdate)  
  89.         {  
  90.             this.dbSet.Attach(entityToUpdate);  
  91.             this.context.Entry(entityToUpdate).State = System.Data.Entity.EntityState.Modified;  
  92.         }  
  93.     }  
  94. }  

Write code in  UnitOfWork.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using CRUD.DataLayer.Entities;  
  7.   
  8. namespace CRUD.DataLayer.Implementation  
  9. {  
  10.   
  11.     /// <summary>  
  12.     /// The UnitOfWork class designed for binding classes to generic class DataAccess. This class is the conversion or binding class  
  13.     /// </summary>  
  14.     /// <seealso cref="System.IDisposable" />  
  15.     public class UnitOfWork : IDisposable  
  16.     {  
  17.         /// <summary>  
  18.         /// Stores the string error message  
  19.         /// </summary>  
  20.         private string errorMessage = string.Empty;  
  21.   
  22.         /// <summary>  
  23.         /// Defines condition for disposing object  
  24.         /// </summary>  
  25.         private bool disposed = false;  
  26.   
  27.         private DataAccess<EmployeeInfo> employeeInfoRepository;  
  28.   
  29.         /// <summary>  
  30.         /// Initializes a new instance of the MyModel class  
  31.         /// </summary>  
  32.         private MyModel objMyModel = new MyModel();  
  33.   
  34.   
  35.         /// <summary>  
  36.         /// Gets the get employee repository.  
  37.         /// </summary>  
  38.         /// <value>  
  39.         /// The get employee repository.  
  40.         /// </value>  
  41.         public DataAccess<EmployeeInfo> GetEmployeeRepository  
  42.         {  
  43.             get  
  44.             {  
  45.                 if (this.employeeInfoRepository == null)  
  46.                 {  
  47.                     this.employeeInfoRepository = new DataAccess<EmployeeInfo>(this.objMyModel);  
  48.                 }  
  49.   
  50.                 return this.employeeInfoRepository;  
  51.             }  
  52.         }  
  53.   
  54.   
  55.         /// <summary>  
  56.         /// This Method will commit the changes to database for the permanent save  
  57.         /// </summary>  
  58.         /// <returns>  
  59.         /// affected rows  
  60.         /// </returns>  
  61.         public int Save()  
  62.         {  
  63.             return this.objMyModel.SaveChanges();  
  64.         }  
  65.         public void Dispose()  
  66.         {  
  67.             this.Dispose(true);  
  68.             GC.SuppressFinalize(this);  
  69.         }  
  70.   
  71.   
  72.         /// <summary>  
  73.         /// This method will dispose the context class object after the uses of that object  
  74.         /// </summary>  
  75.         /// <param name="disposing">parameter true or false for disposing database object</param>  
  76.         protected virtual void Dispose(bool disposing)  
  77.         {  
  78.             if (!this.disposed)  
  79.             {  
  80.                 if (disposing)  
  81.                 {  
  82.                     this.objMyModel.Dispose();  
  83.                 }  
  84.             }  
  85.   
  86.             this.disposed = true;  
  87.         }  
  88.     }  
  89. }  

Now we have completed the data access part.

Step 4

Now we go to the Business Layer.

Here we will create two folders:

  1. Implementation
  2. Interfaces

Now we add interface class like IEmployee.cs and declare our methods.

  1. using System.Collections.Generic;  
  2. using CRUD.DataLayer.Entities;  
  3.   
  4. namespace CRUD.BusinessLayer.Interfaces  
  5. {  
  6.     public interface IEmployee  
  7.     {  
  8.         IEnumerable<EmployeeInfo> EmployeeGet();  
  9.         string EmployeeInsert(EmployeeInfo emp);  
  10.         string EmployeeUpdate(EmployeeInfo emp);  
  11.         string EmployeeDelete(int id);  
  12.     }  
  13. }  

Now we add class Employee.cs in the Implementation folder.

  1. using CRUD.BusinessLayer.Interfaces;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using CRUD.DataLayer.Entities;  
  5. using CRUD.DataLayer.Implementation;  
  6.   
  7.   
  8. namespace CRUD.BusinessLayer.Implementation  
  9. {  
  10.     public class Employee : IEmployee  
  11.     {  
  12.         private UnitOfWork unitOfWork = new UnitOfWork();  
  13.   
  14.         private List<EmployeeInfo> lstEmp = new List<EmployeeInfo>();  
  15.         private EmployeeInfo objEmp = new EmployeeInfo();  
  16.         public IEnumerable<EmployeeInfo> EmployeeGet()  
  17.         {  
  18.             lstEmp = unitOfWork.GetEmployeeRepository.Get().ToList();  
  19.   
  20.             return lstEmp;  
  21.         }  
  22.   
  23.         public string EmployeeUpdate(EmployeeInfo emp)  
  24.         {  
  25.   
  26.             objEmp = unitOfWork.GetEmployeeRepository.GetByID(emp.EmployeeNo);  
  27.   
  28.             if(objEmp !=null)  
  29.             {  
  30.                 objEmp.FirstName = emp.FirstName;  
  31.                 objEmp.LastName = emp.LastName;  
  32.                 objEmp.Address = emp.Address;  
  33.                 objEmp.MobileNo = emp.MobileNo;  
  34.                 objEmp.PostelCode = emp.PostelCode;  
  35.                 objEmp.EmailId = emp.EmailId;  
  36.             }  
  37.             this.unitOfWork.GetEmployeeRepository.Attach(objEmp);  
  38.             int result = this.unitOfWork.Save();  
  39.   
  40.             if(result > 0)  
  41.             {  
  42.                 return "Sucessfully updated of employee records";  
  43.             }  
  44.             else  
  45.             {  
  46.                 return "Updation faild";  
  47.             }  
  48.         }  
  49.   
  50.         public string EmployeeDelete(int id)  
  51.         {  
  52.             var objEmp = this.unitOfWork.GetEmployeeRepository.GetByID(id);  
  53.             this.unitOfWork.GetEmployeeRepository.Delete(objEmp);  
  54.             int deleteData = this.unitOfWork.Save();  
  55.             if(deleteData > 0)  
  56.             {  
  57.                 return "Successfully deleted of employee records";  
  58.             }  
  59.             else  
  60.             {  
  61.                 return "Deletion faild";  
  62.             }  
  63.         }  
  64.   
  65.         public string EmployeeInsert(EmployeeInfo emp)  
  66.         {  
  67.          this.unitOfWork.GetEmployeeRepository.Insert(emp);  
  68.             int inserData =this.unitOfWork.Save();  
  69.   
  70.             if(inserData > 0)  
  71.             {  
  72.                 return "Successfully Inserted of employee records";  
  73.             }  
  74.             else  
  75.             {  
  76.                 return "Insertion faild";  
  77.             }  
  78.         }  
  79.     }  
  80. }  

So now we have completed business layer part, next we will go to the service layer:

Step 5

Now we have to add an API Controller in our Service layer.

Right click the controller and add an API Controller.

Code First Approach

Click add.

Code First Approach

Next we write the code for all operations to perform CRUD Operation in EmplyeeAPI Controller.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Net;  
  4. using System.Net.Http;  
  5. using System.Web.Http;  
  6. using CRUD.DataLayer.Entities;  
  7. using CRUD.BusinessLayer.Implementation;  
  8. using CRUD.BusinessLayer.Interfaces;  
  9.   
  10. namespace CRUD.ServiceLayer.Controllers  
  11. {  
  12.     [System.Web.Http.RoutePrefix("api/Employee")]  
  13.     public class EmployeeAPIController : ApiController  
  14.     {  
  15.   
  16.         IEmployee objEmp = new Employee();  
  17.   
  18.         [System.Web.Http.HttpGet]  
  19.         [System.Web.Http.Route("EmpDetails")]  
  20.         public IEnumerable<EmployeeInfo> GetEmployeeData()  
  21.         {  
  22.             
  23.   
  24.             IEnumerable<EmployeeInfo> empDetail = new List<EmployeeInfo>();  
  25.             try  
  26.             {  
  27.                 empDetail = objEmp.EmployeeGet();  
  28.             }  
  29.             catch (ApplicationException ex)  
  30.             {  
  31.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });  
  32.             }  
  33.             catch (Exception ex)  
  34.             {  
  35.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });  
  36.             }  
  37.   
  38.             return empDetail;  
  39.         }  
  40.   
  41.   
  42.         [System.Web.Http.HttpPost]  
  43.         [System.Web.Http.Route("InsertEmpDetails")]  
  44.         public string InserEmployee(EmployeeInfo objEmpDetails)  
  45.         {  
  46.             string objEmployee;  
  47.             try  
  48.             {  
  49.                 objEmployee = this.objEmp.EmployeeInsert(objEmpDetails);  
  50.             }  
  51.             catch (ApplicationException ex)  
  52.             {  
  53.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });  
  54.             }  
  55.             catch (Exception ex)  
  56.             {  
  57.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });  
  58.             }  
  59.   
  60.             return objEmployee;  
  61.         }  
  62.   
  63.         [System.Web.Http.HttpPut]  
  64.         [System.Web.Http.Route("UpdateEmpDetails")]  
  65.         public string UpdateEmployee(EmployeeInfo objEmpDetails)  
  66.         {  
  67.             string objEmployee;  
  68.             try  
  69.             {  
  70.                 objEmployee = this.objEmp.EmployeeUpdate(objEmpDetails);  
  71.             }  
  72.             catch (ApplicationException ex)  
  73.             {  
  74.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });  
  75.             }  
  76.             catch (Exception ex)  
  77.             {  
  78.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });  
  79.             }  
  80.   
  81.             return objEmployee;  
  82.         }  
  83.         [System.Web.Http.HttpDelete]  
  84.         [System.Web.Http.Route("DeleteEmpData/{id}")]  
  85.         public string DeleteEmployeeData(int id)  
  86.         {  
  87.             string objEmpDetails;  
  88.             try  
  89.             {  
  90.                 objEmpDetails = this.objEmp.EmployeeDelete(id);  
  91.             }  
  92.             catch (ApplicationException ex)  
  93.             {  
  94.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });  
  95.             }  
  96.             catch (Exception ex)  
  97.             {  
  98.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });  
  99.             }  
  100.   
  101.             return objEmpDetails;  
  102.         }  
  103.     }  

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

Code First Approach

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

Code First Approach

Now, we have to consume the Web API service and finally, we have to display records in View.

We will add a class in our Models folder and give it a class name of Rest Client. This is a common class for performing all CRUD operations.

Here, we need to add the URL of our service layer.


Code First Approach

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

 

Write the methods in RestClient Class.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Net.Http;  
  6. using System.Net.Http.Headers;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace PersentationLayer.Models  
  10. {  
  11.     public class RestClient : IDisposable  
  12.     {  
  13.         /// <summary>  
  14.         /// The client  
  15.         /// </summary>  
  16.         private HttpClient client;  
  17.         public const string ApiUri = "http://localhost:52133/";  
  18.         /// <summary>  
  19.         /// Media type used for send data in API  
  20.         /// </summary>  
  21.         public const string MediaTypeJson = "application/json";  
  22.   
  23.         /// <summary>  
  24.         /// Media type used for send data in API  
  25.         /// </summary>  
  26.         public const string MediaTypeXML = "application/XML";  
  27.   
  28.         public const string RequestMsg = "Request has not been processed";  
  29.         public static string ReasonPhrase { get; set; }  
  30.   
  31.         /// <summary>  
  32.         /// Initializes a new instance of the <see cref="RestClient"/> class.  
  33.         /// </summary>  
  34.         public RestClient()  
  35.         {  
  36.             this.client = new HttpClient();  
  37.             this.client.BaseAddress = new Uri(ApiUri);  
  38.             this.client.DefaultRequestHeaders.Accept.Clear();  
  39.             this.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeJson));  
  40.         }  
  41.         public async Task<List<U>> RunAsyncGetAll<T, U>(dynamic uri)  
  42.         {  
  43.             HttpResponseMessage response = await this.client.GetAsync(uri);  
  44.             if (response.IsSuccessStatusCode)  
  45.             {  
  46.                 return await response.Content.ReadAsAsync<List<U>>();  
  47.             }  
  48.             else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)  
  49.             {  
  50.                 throw new ApplicationException(response.ReasonPhrase);  
  51.             }  
  52.             else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)  
  53.             {  
  54.                 throw new Exception(response.ReasonPhrase);  
  55.             }  
  56.   
  57.             throw new Exception(RequestMsg);  
  58.         }  
  59.   
  60.         public async Task<List<U>> RunAsyncGet<T, U>(dynamic uri, dynamic data)  
  61.         {  
  62.             HttpResponseMessage response = await this.client.GetAsync(uri + "/" + data);  
  63.             if (response.IsSuccessStatusCode)  
  64.             {  
  65.                 return await response.Content.ReadAsAsync<List<U>>();  
  66.             }  
  67.             else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)  
  68.             {  
  69.                 throw new ApplicationException(response.ReasonPhrase);  
  70.             }  
  71.             else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)  
  72.             {  
  73.                 throw new Exception(response.ReasonPhrase);  
  74.             }  
  75.   
  76.             throw new Exception(RequestMsg);  
  77.         }  
  78.   
  79.         public async Task<U> RunAsyncPost<T, U>(string uri, T entity)  
  80.         {  
  81.             HttpResponseMessage response = client.PostAsJsonAsync(uri, entity).Result;  
  82.             ReasonPhrase = response.ReasonPhrase;  
  83.             if (response.IsSuccessStatusCode)  
  84.             {  
  85.                 return await response.Content.ReadAsAsync<U>();  
  86.             }  
  87.             else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)  
  88.             {  
  89.                 throw new ApplicationException(response.ReasonPhrase);  
  90.             }  
  91.             else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)  
  92.             {  
  93.                 throw new Exception(response.ReasonPhrase);  
  94.             }  
  95.   
  96.             throw new Exception(RequestMsg);  
  97.         }  
  98.   
  99.         public async Task<U> RunAsyncPut<T, U>(string uri, T entity)  
  100.         {  
  101.             HttpResponseMessage response = await this.client.PutAsJsonAsync(uri, entity);  
  102.             if (response.IsSuccessStatusCode)  
  103.             {  
  104.                 return await response.Content.ReadAsAsync<U>();  
  105.             }  
  106.             else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)  
  107.             {  
  108.                 throw new ApplicationException(response.ReasonPhrase);  
  109.             }  
  110.             else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)  
  111.             {  
  112.                 throw new Exception(response.ReasonPhrase);  
  113.             }  
  114.   
  115.             throw new Exception(RequestMsg);  
  116.         }  
  117.   
  118.         public async Task<U> RunAsyncDelete<T, U>(string uri, dynamic id)  
  119.         {  
  120.             HttpResponseMessage response = await this.client.DeleteAsync(uri + "/" + id);  
  121.             if (response.IsSuccessStatusCode)  
  122.             {  
  123.                 return await response.Content.ReadAsAsync<U>();  
  124.             }  
  125.             else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)  
  126.             {  
  127.                 throw new ApplicationException(response.ReasonPhrase);  
  128.             }  
  129.             else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)  
  130.             {  
  131.                 throw new Exception(response.ReasonPhrase);  
  132.             }  
  133.   
  134.             throw new Exception(RequestMsg);  
  135.         }  
  136.   
  137.         /// <summary>  
  138.         /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.  
  139.         /// </summary>  
  140.         public void Dispose()  
  141.         {  
  142.             this.Dispose(true);  
  143.             GC.SuppressFinalize(this);  
  144.         }  
  145.   
  146.         /// <summary>  
  147.         /// Releases unmanaged and - optionally - managed resources.  
  148.         /// </summary>  
  149.         /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>  
  150.         protected virtual void Dispose(bool disposing)  
  151.         {  
  152.             if (disposing)  
  153.             {  
  154.                 //// dispose managed resources  
  155.                 this.client.Dispose();  
  156.             }  
  157.             //// free native resources  
  158.         }  
  159.     }  
  160. }  

Add one more class in Models folder for declaring all entities of emplyee.

Employee.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace PersentationLayer.Models  
  7. {  
  8.     public class Employee  
  9.     {  
  10.             public int EmployeeNo { get; set; }  
  11.             public string FirstName { get; set; }  
  12.             public string LastName { get; set; }  
  13.   
  14.             public string Address { get; set; }  
  15.             public string MobileNo { get; set; }  
  16.             public string PostelCode { get; set; }  
  17.             public string EmailId { get; set; }  
  18.         }  
  19. }    

After that, we will write all the code in MVC Controller class.

  1. using System;  
  2. using System.Web.Mvc;  
  3. using PersentationLayer.Models;  
  4. using System.Threading.Tasks;  
  5. using System.Net.Http;  
  6. using System.Net;  
  7. using System.Web.Http;  
  8.   
  9. namespace PersentationLayer.Controllers  
  10. {  
  11.     public class EmployeeController : Controller  
  12.     {  
  13.   
  14.         private RestClient restClient = new RestClient();  
  15.         // GET: Employee  
  16.         public ActionResult EmployeeDetails()  
  17.         {  
  18.             return this.View();  
  19.         }  
  20.         public async Task<ActionResult> EmpInfoData()  
  21.         {  
  22.             try  
  23.             {  
  24.   
  25.                 return this.Json(await this.restClient.RunAsyncGetAll<Employee, Employee>("api/Employee/EmpDetails"), JsonRequestBehavior.AllowGet);  
  26.             }  
  27.             catch (ApplicationException ex)  
  28.             {  
  29.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });  
  30.   
  31.             }  
  32.             catch (Exception ex)  
  33.             {  
  34.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });  
  35.             }  
  36.         }  
  37.   
  38.         public async Task<ActionResult> InsertEmployeeInfo(Employee objEmp)  
  39.         {  
  40.             try  
  41.             {  
  42.                 return this.Json(await this.restClient.RunAsyncPost<Employee, string>("api/Employee/InsertEmpDetails", objEmp));  
  43.             }  
  44.             catch (ApplicationException ex)  
  45.             {  
  46.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });  
  47.             }  
  48.             catch (Exception ex)  
  49.             {  
  50.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });  
  51.             }  
  52.         }  
  53.         public async Task<ActionResult> UpdateEmployeeInfo(Employee objEmp)  
  54.         {  
  55.             try  
  56.             {  
  57.                 return this.Json(await this.restClient.RunAsyncPut<Employee, string>("api/Employee/UpdateEmpDetails", objEmp));  
  58.             }  
  59.             catch (ApplicationException ex)  
  60.             {  
  61.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });  
  62.             }  
  63.             catch (Exception ex)  
  64.             {  
  65.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });  
  66.             }  
  67.         }  
  68.   
  69.   
  70.         public async Task<ActionResult> DeleteEmployeeInfo(int id)  
  71.         {  
  72.             try  
  73.             {  
  74.                 return this.Json(await this.restClient.RunAsyncDelete<int, string>("api/Employee/DeleteEmpData", id));  
  75.             }  
  76.             catch (ApplicationException ex)  
  77.             {  
  78.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });  
  79.             }  
  80.             catch (Exception ex)  
  81.             {  
  82.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });  
  83.             }  
  84.         }  
  85.   
  86.     }  
  87. }  

We will display all our records in View however here we will use jqGrid for viewing the records. First, we have to add jqGrid library. Go to Manage NuGet Package, search for jqGrid library, and install.

Code First Approach

Now, we will write code related to jqGrid so we will take a separate JavaScript file and give it a name like EmpDetails.js, now write this code...

  1. /// <reference path="jqGrid/jquery.jqGrid.js" />  
  2.   
  3. var EmployeeDetails = {  
  4.   
  5.     GetEmpData: function () {  
  6.         $("#list").jqGrid({  
  7.             url: '/Employee/EmpInfoData',  
  8.             datatype: 'json',  
  9.             mtype: 'Get',  
  10.             colModel: [  
  11.                 {  
  12.                     key: true, hidden: true, name: 'EmployeeNo', index: 'EmployeeNo', editable: true  
  13.                 },  
  14.   
  15.                           { key: false, name: 'FirstName', index: 'FirstName', width: 245, editable: true, editrules: { required: true }, },  
  16.   
  17.                             { name: 'LastName', index: 'LastName', width: 245, editable: true, editrules: { required: true }, },  
  18.                                { name: 'Address', index: 'Address', width: 245, editable: true, editrules: { required: true }, },  
  19.   
  20.                           {  
  21.                               name: 'MobileNo', index: 'MobileNo', width: 245, editable: true, editrules: { required: true }, editoptions: {  
  22.                                   maxlength: "10", dataInit: function (element) {  
  23.                                       $(element).keypress(function (e) {  
  24.                                           if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {  
  25.                                               alert("Accept only numeric value and only ten digits");  
  26.                                               return false;  
  27.                                           }  
  28.                                       });  
  29.                                   }  
  30.                               }  
  31.                           },  
  32.   
  33.                           {  
  34.                               name: 'PostelCode', index: 'PostelCode', width: 145, editable: true, editrules: { required: true }, editoptions: {  
  35.                                   maxlength: "6", dataInit: function (element) {  
  36.                                       $(element).keypress(function (e) {  
  37.   
  38.                                           if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {  
  39.   
  40.                                               alert("Accept only numeric value and only six digits");  
  41.                                               return false;  
  42.                                           }  
  43.                                       });  
  44.                                   }  
  45.                               }  
  46.                           },  
  47.                             { name: 'EmailId', index: 'EmailId', width: 245, editable: true, editrules: { required: true }, }  
  48.             ],  
  49.             pager: jQuery('#pager'),  
  50.             rowNum: 10,  
  51.             loadonce: true,  
  52.             rowList: [10, 20, 30, 40],  
  53.             height: '100%',  
  54.             viewrecords: true,  
  55.             caption: 'Employee Details',  
  56.             emptyrecords: 'No records to display',  
  57.             jsonReader: {  
  58.                 repeatitems: false,  
  59.                 root: function (obj) { return obj; },  
  60.                 page: "page",  
  61.                 total: "total",  
  62.                 records: "records",  
  63.                 repeatitems: false,  
  64.                 EmployeeNo: "0"  
  65.             },  
  66.             autowidth: true,  
  67.             multiselect: false  
  68.         }).navGrid('#pager', { add: false, edit: true, del: true, search: false, refresh: true },  
  69.        {  
  70.            // edit options  
  71.            zIndex: 1000,  
  72.            url: '/Employee/UpdateEmployeeInfo',  
  73.            closeOnEscape: true,  
  74.            closeAfterEdit: true,  
  75.            recreateForm: true,  
  76.            loadonce: true,  
  77.            align: 'center',  
  78.            afterComplete: function (response) {  
  79.                GetEmpData()  
  80.                if (response.responseText) {  
  81.                     
  82.                    alert(response.responseText);  
  83.                }  
  84.            }  
  85.        }, {},  
  86.        {  
  87.            // delete options  
  88.            zIndex: 1000,  
  89.            url: '/Employee/DeleteEmployeeInfo',  
  90.            closeOnEscape: true,  
  91.            closeAfterdel: true,  
  92.            recreateForm: true,  
  93.            msg: "Are you sure you want to delete this task?",  
  94.            afterComplete: function (response) {  
  95.                if (response.responseText) {  
  96.                    $("#alert-Grid").html("<b>" + response.responseText + "</b>");  
  97.                    $("#alert-Grid").show();  
  98.                    $("#alert-Grid").delay(3000).fadeOut("slow");  
  99.                }  
  100.            }  
  101.        });  
  102.     },  
  103.     insertEmployeeDetails: function () {  
  104.        
  105.         $("#btnSubmit").click(function () {  
  106.            
  107.             $.ajax(  
  108.             {  
  109.                 type: "POST"//HTTP POST Method    
  110.                 url: "/Employee/InsertEmployeeInfo"// Controller/View     
  111.                 data: { //Passing data    
  112.   
  113.                     FirstName: $("#txtFName").val(), //Reading text box values using Jquery     
  114.                     LastName: $("#txtLName").val(),  
  115.                     Address: $("#txtAddress").val(),  
  116.                     MobileNo: $("#txtMobileNo").val(),  
  117.                     PostelCode: $("#txtPinCode").val(),  
  118.                     EmailId: $("#txtEmail").val()  
  119.                 },  
  120.                 success: function (data) {  
  121.                     alert(data);  
  122.                     $("##alert-danger").html("<b>" + data + "</b>");  
  123.                     $("##alert-danger").show();  
  124.                     $("##alert-danger").delay(10000).fadeOut("slow");  
  125.                 },  
  126.                 error: function (data) {  
  127.                     GetEmpData();  
  128.                     //var r = data.responseText;  
  129.                     //var errorMessage = r.Message;  
  130.                     $("##alert-danger").html("<b>" + data + "</b>");  
  131.                     $("##alert-danger").show();  
  132.                     $("##alert-danger").delay(10000).fadeOut("slow");  
  133.                 }  
  134.             });  
  135.         });  
  136.     }  
  137. }  

Now, let's design our UI with HTML in View.

  1. @{  
  2.     ViewBag.Title = "EmployeeDetails";  
  3. }  
  4.   
  5. <link href="~/themes/jquery-ui-1.12.1.custom/jquery-ui.css" rel="stylesheet" />  
  6. <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />  
  7.   
  8. <script src="~/Scripts/jquery-1.9.1.js"></script>  
  9. <script src="~/Scripts/jquery-ui-1.10.0.js"></script>  
  10. <script src="~/Scripts/i18n/grid.locale-en.js"></script>  
  11. <script src="~/Scripts/jquery.jqGrid.min.js"></script>  
  12. <script src="~/Scripts/EmpDetails.js"></script>  
  13. <br />  
  14. <div class="row">  
  15.     <div class="col-xs-4 col-md-2"></div>  
  16.     <div class="col-xs-6 col-md-8" ng-hide="showHide">  
  17.         <div class="panel panel-default">  
  18.             <div class="panel-heading" style="background-color:#4B7082;color:white"><h4 align="center">Add New Employee Records</h4></div>  
  19.             <div class="panel-body">  
  20.                 <div class="row">  
  21.                     <form class="form-inline" id="form1">  
  22.                        
  23.                         <div class="col-md-5" style="padding-left:80px;">  
  24.                             <div class="form-inline">  
  25.                                 <label for="" id="label">First Name</label>  
  26.                                 <input type="text" class="form-control" required id="txtFName">  
  27.                             </div>  
  28.                             <br />  
  29.                             <div class="form-inline">  
  30.                                 <label for="" id="label">Address</label>  
  31.                                 <input type="text" class="form-control" required id="txtAddress">  
  32.   
  33.                             </div>  
  34.                             <br />  
  35.                             <div class="form-inline">  
  36.                                 <label for="" id="label">Pin Code</label>  
  37.                                 <input type="text" class="form-control" required id="txtPinCode">  
  38.   
  39.                             </div>  
  40.                         </div>  
  41.                         <div class="col-md-5"  style="padding-left:80px;">  
  42.                             <div class="form-inline">  
  43.                                 <label for="" id="label">Last Name</label>  
  44.                                 <input type="text" required id="txtLName" class="form-control">  
  45.                             </div>  
  46.                             <br />  
  47.                             <div class="form-inline">  
  48.                                 <label for="" id="label">Mobile Number</label>  
  49.                                 <input type="text" class="form-control" required id="txtMobileNo">  
  50.   
  51.                             </div><br />  
  52.                             <div class="form-inline">  
  53.                                 <label for="" id="label">Email Id</label>  
  54.                                 <input type="text" class="form-control" required id="txtEmail">  
  55.   
  56.                             </div>  
  57.                             <br />  
  58.                                     <input type="submit" class="btn btn-success"  id="btnSubmit" value="Submit" />  
  59.                                 
  60.                             </div>  
  61.                          
  62.                      
  63.                     </form>  
  64.                 </div>  
  65.   
  66.             </div>  
  67.         </div>  
  68.     </div>  
  69.     <div class="col-xs-6 col-md-2"></div>  
  70. </div>  
  71. <div class="row">  
  72.     <div class="col-md-10 col-md-offset-1">  
  73.         <div class="alert alert-danger" role="alert" id="alert-Grid"></div>  
  74.         <table align="center" id="list"></table>  
  75.         <div id="pager"></div>  
  76.   
  77.     </div>  
  78. </div>  

Now, we will callour jqGrid methods in View. Write this code in View page.

  1. <script type="text/javascript">  
  2.     $(function () {  
  3.         $("#alert-Grid").hide();  
  4.         EmployeeDetails.GetEmpData();  
  5.         EmployeeDetails.insertEmployeeDetails();  
  6.   
  7.     });           
  8. </script>  

So, we can see that this is my final View.

Code First Approach

We will insert, update, and delete our records.

Code First Approach

Here, it is working with all related validation. We can see that the mobile number should be numeric but if we try to enter it alphabetically, then it will show an error.

Thanks and happy coding.