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

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

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. namespace CRUD.BusinessLayer.Interfaces
  4. {
  5. public interface IEmployee
  6. {
  7. IEnumerable<EmployeeInfo> EmployeeGet();
  8. string EmployeeInsert(EmployeeInfo emp);
  9. string EmployeeUpdate(EmployeeInfo emp);
  10. string EmployeeDelete(int id);
  11. }
  12. }

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

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

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

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. namespace PersentationLayer.Models
  6. {
  7. public class Employee
  8. {
  9. public int EmployeeNo { get; set; }
  10. public string FirstName { get; set; }
  11. public string LastName { get; set; }
  12. public string Address { get; set; }
  13. public string MobileNo { get; set; }
  14. public string PostelCode { get; set; }
  15. public string EmailId { get; set; }
  16. }
  17. }

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

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

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

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