Consuming ASP.Net WEB API Using ASP.Net MVC4

Introduction 

This article explains how to consume the ASP.Net Web API using ASP.NET MVC4 with repository pattern.

Database structure

Create a table in a database for Employee to store employee information.

  1. CREATE TABLE [dbo].[Employe]
  2. (  
  3.  [Empid] [intNOT NULL,  
  4.  [Empname] [varchar](50) NULL,  
  5.  [Empcity] [varchar](50) NULL,  
  6.  [Empaddress] [varchar](50) NULL,  
  7.   
  8. )  

Create Web API Application

Go to File => New => Project. Choose "ASP.NET MVC 4 Web Application" from the list, then provide the application name as you whish and click the OK button then select Web API. Set the path to the location input where you want to create the application.

Our solution has three class libraries as in the following:


1. Module.interface1

Inside this library we have a folder with the name IBL and IBL contains the interface with the name IEmploye. And IEmploye contains the declaration of some methods defined as follows:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using ModelClasses;  
  7.   
  8. namespace module.interface1.IBL  
  9. {  
  10.    public interface IEmploye  
  11.     {  
  12.   
  13.    bool InsertEmploye(EmployeModel employee);  
  14.   
  15.    List<EmployeModel> GetAllEmploye();  
  16.   
  17.    List<EmployeModel> GetByid(int Empid);  
  18.   
  19.    bool UpdateEmploye(EmployeModel employee, int Empid);  
  20.   
  21.    //bool UpdateEmp(EmployeModel employee, int Empid);  
  22.    bool DeleteEmp(int Empid);  
  23.   
  24.   
  25.     }  
  26.   
  27. }  

2. ModelClass

Inside this library here we have a class with the name EmployeModel and EmployeModel contains the properties defined as follows.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace ModelClasses  
  8. {  
  9.     #region Employee  
  10.     public class EmployeModel  
  11.     {  
  12.         #region Properties  
  13.         public int Empid { getset; }  
  14.         public string Empname { getset; }  
  15.         public string Empcity { getset; }  
  16.         public string Empaddress { getset; }  
  17.          
  18.         #endregion  
  19.   
  20.     }  
  21.     #endregion  
  22. }  
3. Module.source

Inside this library here we have the two folders BL and DL. 

In the Bussiness Logic (BL) folder we have a class named EmployeBL. It contains the business logic defined as follows:

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5. using System.Threading.Tasks;    
  6. using ModelClasses;    
  7. using module.interface1;    
  8. using Module.source.DL;    
  9. using System.IO;    
  10. using Microsoft.Practices.Unity;    
  11.     
  12.     
  13. namespace Module.source.BL    
  14. {    
  15.     public class EmployeBL : module.interface1.IBL.IEmploye    
  16.     {    
  17.     
  18.     
  19.         public bool InsertEmploye(EmployeModel employee)    
  20.         {    
  21.             bool employeelist = false;    
  22.             try    
  23.             {    
  24.                 employeelist = new EmployeDAL().InsertEmploye(employee);    
  25.             }    
  26.             catch (Exception ex)    
  27.             {    
  28.     
  29.                 throw ex;    
  30.             }    
  31.     
  32.             return employeelist;    
  33.         }    
  34.     
  35.     
  36.         public List<EmployeModel> GetAllEmploye()    
  37.         {    
  38.             List<EmployeModel> employelist = null;    
  39.             try    
  40.             {    
  41.     
  42.                 employelist = new EmployeDAL().GetAllEmploye();    
  43.     
  44.     
  45.             }    
  46.             catch (Exception ex)    
  47.             {    
  48.                 throw ex;    
  49.     
  50.             }    
  51.             return employelist;    
  52.         }    
  53.     
  54.         public List<EmployeModel> GetByid(int Empid)    
  55.         {    
  56.             List<EmployeModel> readbyid = null;    
  57.             try    
  58.             {    
  59.     
  60.                 readbyid = new EmployeDAL().GetByid(Empid);    
  61.     
  62.             }    
  63.             catch (Exception ex)    
  64.             {    
  65.     
  66.                 throw ex;    
  67.             }    
  68.             return readbyid;    
  69.     
  70.         }    
  71.     
  72.     
  73.     
  74.         public bool UpdateEmploye(EmployeModel employee, int Empid)    
  75.         {    
  76.             bool updateid = false;    
  77.     
  78.             try    
  79.             {    
  80.     
  81.                 updateid = new EmployeDAL().UpdateEmploye(employee, Empid);    
  82.     
  83.             }    
  84.             catch (Exception ex)    
  85.             {    
  86.     
  87.                 throw ex;    
  88.             }    
  89.     
  90.             return updateid;    
  91.         }    
  92.     
  93.     
  94.     
  95.         public bool DeleteEmp(int Empid)    
  96.         {    
  97.             bool deleteemploye = false;    
  98.             try    
  99.             {    
  100.                 deleteemploye = new EmployeDAL().DeleteEmp(Empid);    
  101.             }    
  102.             catch (Exception ex)    
  103.             {    
  104.     
  105.                 throw ex;    
  106.                 
  107.             }    
  108.             return deleteemploye;    
  109.                 
  110.         }    
  111.     }    
  112. }   
In the Data Access layer (DL) folder I have a class named EmployeDL. It contains the data access logic defined as follows. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using ModelClasses;  
  7. using Microsoft.Practices.EnterpriseLibrary.Data.Sql;  
  8. using System.Configuration;  
  9. using System.Data.Common;  
  10. using System.Data;  
  11. using Module.source.DL;  
  12. using Microsoft.Practices.Unity;  
  13. using Module.source.BL;  
  14.   
  15. namespace Module.source.DL  
  16. {  
  17.   public  class EmployeDAL : DataAccessComponent  
  18.     {  
  19.         string con = ConfigurationManager.ConnectionStrings["conster"].ConnectionString;  
  20.   
  21.   
  22.         public bool InsertEmploye(EmployeModel employee)  
  23.         {  
  24.   
  25.             bool employelist = false;  
  26.             SqlDatabase db = new SqlDatabase(con);  
  27.             using (DbCommand objCMD = db.GetStoredProcCommand("usp_insertemp"))  
  28.             {  
  29.   
  30.                 db.AddInParameter(objCMD, "@Empid", DbType.Int32, employee.Empid);  
  31.                 db.AddInParameter(objCMD, "@Empname", DbType.String, employee.Empname);  
  32.                 db.AddInParameter(objCMD, "@Empcity", DbType.String, employee.Empcity);  
  33.                 db.AddInParameter(objCMD, "@Empaddress", DbType.String, employee.Empaddress);  
  34.                 db.AddOutParameter(objCMD, "@status", DbType.Int16, 0);  
  35.                 try  
  36.                 {  
  37.                     db.ExecuteNonQuery(objCMD);  
  38.                     employelist = Convert.ToBoolean(db.GetParameterValue(objCMD, "@Status"));  
  39.   
  40.                 }  
  41.                 catch (Exception ex)  
  42.                 {  
  43.   
  44.                     throw ex;  
  45.   
  46.                 }  
  47.   
  48.             }  
  49.   
  50.             return employelist;  
  51.   
  52.         }  
  53.   
  54.   
  55.         public List<EmployeModel> GetAllEmploye()  
  56.         {  
  57.             List<EmployeModel> employlist = null;  
  58.             SqlDatabase db = new SqlDatabase(con);  
  59.             using (DbCommand objcmd = db.GetStoredProcCommand("get_allrecored"))  
  60.             {  
  61.                 try  
  62.                 {  
  63.                     // return db.ExecuteDataSet(objcmd);  
  64.   
  65.                     using (DataTable dataTable = db.ExecuteDataSet(objcmd).Tables[0])  
  66.                     {  
  67.   
  68.                         employlist = ConvertTo<EmployeModel>(dataTable);  
  69.                     }  
  70.   
  71.                 }  
  72.                 catch (Exception ex)  
  73.                 {  
  74.   
  75.                     throw ex;  
  76.                 }  
  77.   
  78.   
  79.             }  
  80.             return employlist;  
  81.   
  82.         }  
  83.   
  84.         public List<EmployeModel> GetByid( int Empid)  
  85.         {  
  86.             EmployeModel emps = new EmployeModel();  
  87.             List<EmployeModel> recordbyid = null;  
  88.             SqlDatabase db = new SqlDatabase(con);  
  89.              
  90.             using (DbCommand objcmd = db.GetStoredProcCommand("get_byid"))  
  91.             {  
  92.   
  93.                 db.AddInParameter(objcmd, "@Empid", DbType.Int32, Empid);  
  94.   
  95.                 try  
  96.                 {  
  97.                     using (IDataReader objDataReader = db.ExecuteReader(objcmd))  
  98.                     {  
  99.   
  100.                         while (objDataReader.Read())  
  101.                         {  
  102.   
  103.                             emps.Empname = objDataReader["Empname"].ToString();  
  104.                             emps.Empcity = objDataReader["Empname"].ToString();  
  105.                             emps.Empaddress = objDataReader["Empaddress"].ToString();  
  106.                             recordbyid.Add(emps);  
  107.   
  108.                         }  
  109.                     }  
  110.   
  111.                 }  
  112.                 catch (Exception ex)  
  113.                 {  
  114.   
  115.   
  116.                     throw ex;  
  117.                 }  
  118.             }  
  119.             return recordbyid;  
  120.   
  121.         }  
  122.   
  123.         public bool UpdateEmploye(EmployeModel employee, int Empid)  
  124.         {  
  125.             bool updatelist = false;  
  126.   
  127.             SqlDatabase db = new SqlDatabase(con);  
  128.   
  129.             using (DbCommand objcmd = db.GetStoredProcCommand("update_employedata"))  
  130.             {  
  131.   
  132.                 db.AddInParameter(objcmd, "@Empid", DbType.String, Empid);  
  133.                 db.AddInParameter(objcmd, "@Empname", DbType.String, employee.Empname);  
  134.                 db.AddInParameter(objcmd, "@Empcity", DbType.String, employee.Empcity);  
  135.                 db.AddInParameter(objcmd, "@Empaddress", DbType.String, employee.Empaddress);  
  136.                 db.AddOutParameter(objcmd, "@status",DbType.Int16,1);  
  137.                    
  138.                 try  
  139.                 {  
  140.                     db.ExecuteNonQuery(objcmd);  
  141.   
  142.                     updatelist = Convert.ToBoolean(db.GetParameterValue(objcmd, "@Status"));  
  143.   
  144.                 }  
  145.                 catch (Exception ex)  
  146.                 {  
  147.   
  148.                     throw ex;  
  149.                 }  
  150.   
  151.             }  
  152.             return updatelist;  
  153.   
  154.         }  
  155.   
  156.         public bool UpdateEmp(EmployeModel employee, int Empid)  
  157.         {  
  158.   
  159.             bool updatelist = false;  
  160.   
  161.             SqlDatabase db = new SqlDatabase(con);  
  162.             using (DbCommand objcmd = db.GetStoredProcCommand("update_employedata"))  
  163.             {  
  164.                 db.AddInParameter(objcmd, "@Empid", DbType.String, Empid);  
  165.                 db.AddInParameter(objcmd, "@Empname", DbType.String, employee.Empname);  
  166.                 db.AddInParameter(objcmd, "@Empcity", DbType.String, employee.Empcity);  
  167.                 db.AddInParameter(objcmd, "@Empaddress", DbType.String, employee.Empaddress);  
  168.                 db.AddOutParameter(objcmd, "@status", DbType.Int32, 1);  
  169.                 //db.AddParameter(objcmd, "@Empname", DbType.String, employee.Empname);  
  170.                 try  
  171.                 {  
  172.   
  173.                     db.ExecuteNonQuery(objcmd);  
  174.                     updatelist = Convert.ToBoolean(db.GetParameterValue(objcmd, "@status"));  
  175.   
  176.                     //updatelist = Convert.ToBoolean(db.GetParameterValue(objcmd, "@status"));  
  177.   
  178.   
  179.                 }  
  180.                 catch (Exception ex)  
  181.                 {  
  182.   
  183.                     throw ex;  
  184.                 }  
  185.             }  
  186.             return updatelist;  
  187.           
  188.           
  189.         }  
  190.   
  191.   
  192.         public bool DeleteEmp(int Empid)  
  193.         {  
  194.   
  195.             bool deleteemploye = false;  
  196.             SqlDatabase db = new SqlDatabase(con);  
  197.             using (DbCommand objcmd = db.GetStoredProcCommand("Delete_employedata"))  
  198.             {  
  199.   
  200.                 db.AddInParameter(objcmd, "@Empid", DbType.String, Empid);  
  201.                 db.AddOutParameter(objcmd, "@status", DbType.Int32, 1);  
  202.                 try  
  203.                 {  
  204.   
  205.   
  206.                     db.ExecuteNonQuery(objcmd);  
  207.                     deleteemploye = Convert.ToBoolean(db.GetParameterValue(objcmd, "@status"));  
  208.   
  209.   
  210.                 }  
  211.                 catch (Exception ex)  
  212.                 {  
  213.   
  214.                     throw ex;  
  215.                 }  
  216.               
  217.               
  218.             }  
  219.   
  220.             return deleteemploye;  
  221.           
  222.           
  223.         }  
  224.  
  225.            
  226.     }  
  227. }  

Let's switch to our Web API controller.

Create a controller class for Employee

Now we can create an Employe controller that has an action for all the CRUD operations of the employee.

In the following code we will use the Repository pattern. First understand why we use a repository in our application. The repository creates an abstraction layer between the data access layer and the business logic layer of an application and if we want to use outside code in our application then we will use it in our applications Repository pattern.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using System.Data.Common;  
  8. using ModelClasses;  
  9. using module.interface1.IBL;  
  10. using Module.source.BL;  
  11. using Microsoft.Practices.Unity;  
  12.   
  13. namespace webapitest.Controllers  
  14. {  
  15.     public class EmployeController : ApiController  
  16.     {  
  17.         static readonly IEmploye repository = new EmployeBL();  
  18.          
  19.          
  20.         HttpResponseMessage response = new HttpResponseMessage();  
  21.   
  22.   
  23.   
  24.         [HttpPost, ActionName("InsertEmploye")]  
  25.         public HttpResponseMessage InsertEmploye(EmployeModel employee)  
  26.         {  
  27.   
  28.             var resultobj = repository.InsertEmploye(employee);  
  29.            if (resultobj !=false)  
  30.            {  
  31.                 response = Request.CreateResponse(HttpStatusCode.OK, "value inserted");  
  32.            }  
  33.             return response;  
  34.           
  35.         }  
  36.   
  37.         [HttpGet, ActionName("GetAllEmploye")]  
  38.         public HttpResponseMessage GetAllEmploye()  
  39.         {  
  40.   
  41.   
  42.             var resultobj = repository.GetAllEmploye();  
  43.             if (resultobj != null)  
  44.             {  
  45.   
  46.                 response = Request.CreateResponse<List<EmployeModel>>(HttpStatusCode.OK, resultobj);  
  47.               
  48.             }  
  49.             return response;  
  50.           
  51.         }  
  52.   
  53.         [HttpGet, ActionName("GetByid")]  
  54.         public HttpResponseMessage GetByid( int Empid)  
  55.         {  
  56.   
  57.             var resultobj = repository.GetByid(Empid);  
  58.   
  59.             if (resultobj != null)  
  60.             {  
  61.                 response = Request.CreateResponse(HttpStatusCode.OK, resultobj);  
  62.               
  63.             }  
  64.             return response;  
  65.           
  66.         }  
  67.   
  68.   
  69.         [HttpPut,ActionName("UpdateEmploye")]  
  70.   
  71.         public HttpResponseMessage UpdateEmploye(  int Empid,EmployeModel employee)  
  72.         {  
  73.   
  74.             var resultobj = repository.UpdateEmploye(employee, Empid);  
  75.   
  76.            if (resultobj !=false)  
  77.            {  
  78.                 response = Request.CreateResponse(HttpStatusCode.OK, "record update");  
  79.            }  
  80.             return response;  
  81.           
  82.         }  
  83.   
  84.       
  85.           [HttpDelete,ActionName("DeleteEmp")]  
  86.          public HttpResponseMessage  DeleteEmp(int Empid)  
  87.           {  
  88.           
  89.             var resultobj= repository.DeleteEmp(Empid);  
  90.   
  91.             if (resultobj != false)  
  92.             {  
  93.   
  94.                 response = Request.CreateResponse(HttpStatusCode.OK, " record successfuly deleted");  
  95.               
  96.             }  
  97.   
  98.             return response;  
  99.           
  100.         }  
  101.           
  102.     }  
  103. }  
Now we will cerate a MVC application. Right-click on the solution.



Choose ASP.NET MVC appliaction and click the OK button and select Basic then click the OK button.

Create Model Class 

The MVC model contains all the application logic validation, Business Logic and data access logic. We can create an Emps class under the Model Folder.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.ComponentModel.DataAnnotations;  
  6.   
  7. namespace Web.Models  
  8. {  
  9.     public class Emps  
  10.     {  
  11.   
  12.         [Display(Name = "Employe Id")]  
  13.         public int Empid { getset; }  
  14.         [Display(Name = "Employe Name")]  
  15.         public string Empname { getset; }  
  16.         [Display(Name = "Employe City")]  
  17.         public string Empcity { getset; }  
  18.         [Display(Name = "Employe Address")]  
  19.         public string Empaddress { getset; }  
  20.     }  
  21. }  
Create controller class for Employe

Now we can create an Employee controller that has an action for all the CRUD operations of the employee.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Net.Http.Headers;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8. using Web.Models;  
  9.   
  10. namespace Web.Controllers  
  11. {  
  12.     public class EmployeController : Controller  
  13.     {  
  14.   
  15.         DataClasses1DataContext db = new DataClasses1DataContext();  
  16.         //  
  17.         // GET: /Employe/  
  18.   
  19.         public ActionResult Index()  
  20.         {  
  21.   
  22.             return View();  
  23.         }  
  24.   
  25.         [HttpGet, ActionName("Getcollegelist")]  
  26.         public ActionResult GetAllEmploye()  
  27.         {  
  28.             HttpClient client = new HttpClient();  
  29.             client.BaseAddress = new Uri("http://localhost:56129/");  
  30.             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  31.             HttpResponseMessage response = client.GetAsync("api/Employe/GetAllEmploye").Result;  
  32.             List<Emps> cd = response.Content.ReadAsAsync<List<Emps>>().Result;  
  33.             return View("~/Views/GetEmploye.cshtml", cd);  
  34.          
  35.         }  
  36.   
  37.         public ActionResult Create()  
  38.         {  
  39.             return View();  
  40.           
  41.         }  
  42.   
  43.         [HttpPost, ActionName("Create")]  
  44.         public ActionResult Create(Emps e1)  
  45.         {  
  46.             HttpClient client = new HttpClient();  
  47.             client.BaseAddress = new Uri("http://localhost:56129/");  
  48.             //client.DefaultRequestHeaders.Add("",)  
  49.   
  50.             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  51.            // HttpResponseMessage response = client.PostAsJsonAsync("api/Employe/InsertEmploye",e1).Result;  
  52.             HttpResponseMessage response = client.PostAsJsonAsync("api/Employe/InsertEmploye",e1).Result;  
  53.           
  54.             return RedirectToAction("Getcollegelist");   
  55.         }  
  56.   
  57.   
  58.         public ActionResult Edit(int id )  
  59.         {  
  60.             Emps model = db.Employes.Where(val => val.Empid == id).Select(val => new Emps()  
  61.             {  
  62.   
  63.                 Empid = val.Empid,  
  64.                 Empaddress = val.Empaddress,  
  65.                 Empcity = val.Empcity,  
  66.                 Empname = val.Empname,  
  67.   
  68.   
  69.   
  70.             }).SingleOrDefault();  
  71.   
  72.             return View( model);  
  73.         }  
  74.         [HttpPost]  
  75.         public ActionResult Edit(Emps model,int id)  
  76.         {  
  77.             HttpClient client = new HttpClient();  
  78.             client.BaseAddress = new Uri("http://localhost:56129/");  
  79.             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  80.             HttpResponseMessage response = client.PutAsJsonAsync("api/Employe/UpdateEmploye?Empid="+id, model).Result;  
  81.   
  82.             return RedirectToAction("Getcollegelist");  
  83.           
  84.         }  
  85.   
  86.         public ActionResult  Delete( int id)  
  87.         {  
  88.             HttpClient client = new HttpClient();  
  89.             client.BaseAddress = new Uri("http://localhost:56129/");  
  90.             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  91.             HttpResponseMessage response = client.DeleteAsync("api/Employe/DeleteEmp?Empid=" +id).Result;  
  92.             return RedirectToAction("Getcollegelist");  
  93.           
  94.         }  
  95.   
  96.         public ActionResult Details(int id)  
  97.         {  
  98.   
  99.             Emps model = db.Employes.Where(val => val.Empid == id).Select(val => new Emps()  
  100.                 {  
  101.   
  102.                     Empid = val.Empid,  
  103.                     Empaddress = val.Empaddress,  
  104.                     Empname = val.Empname,  
  105.                     Empcity = val.Empcity  
  106.                 }).SingleOrDefault();  
  107.                  return View(model);  
  108.           
  109.         }  
  110.         
  111. }  
  112.     }  
Now we will create a view for each operation of the employee.

Let's see each view with code.

Create a view to add a new employee

Now we can create a view (Create.cshtml).

  1. @model Web.Models.Emps  
  2.   
  3. @{  
  4.     ViewBag.Title = "Create";  
  5. }  
  6.   
  7. <h2>Create</h2>  
  8.   
  9. @using (Html.BeginForm()) {  
  10.     @Html.ValidationSummary(true)  
  11.   
  12.     <fieldset>  
  13.         <legend>Emps</legend>  
  14.   
  15.         <div class="editor-label">  
  16.             @Html.LabelFor(model => model.Empid)  
  17.         </div>  
  18.         <div class="editor-field">  
  19.             @Html.EditorFor(model => model.Empid)  
  20.             @Html.ValidationMessageFor(model => model.Empid)  
  21.         </div>  
  22.   
  23.         <div class="editor-label">  
  24.             @Html.LabelFor(model => model.Empname)  
  25.         </div>  
  26.         <div class="editor-field">  
  27.             @Html.EditorFor(model => model.Empname)  
  28.             @Html.ValidationMessageFor(model => model.Empname)  
  29.         </div>  
  30.   
  31.         <div class="editor-label">  
  32.             @Html.LabelFor(model => model.Empcity)  
  33.         </div>  
  34.         <div class="editor-field">  
  35.             @Html.EditorFor(model => model.Empcity)  
  36.             @Html.ValidationMessageFor(model => model.Empcity)  
  37.         </div>  
  38.   
  39.         <div class="editor-label">  
  40.             @Html.LabelFor(model => model.Empaddress)  
  41.         </div>  
  42.         <div class="editor-field">  
  43.             @Html.EditorFor(model => model.Empaddress)  
  44.             @Html.ValidationMessageFor(model => model.Empaddress)  
  45.         </div>  
  46.   
  47.         <p>  
  48.             <input type="submit" value="Create" />  
  49.         </p>  
  50.     </fieldset>  
  51. }  
  52.   
  53. <div>  
  54.     @Html.ActionLink("Back to List", "Index")  
  55. </div>  
  56.   
  57. @section Scripts {  
  58.     @Scripts.Render("~/bundles/jqueryval")  
  59. }  

The following is the output of the preceding code:

Show list of all Employees

We can create a view with the name GetEmploye inside the views folder.

  1. @model IEnumerable<Web.Models.Emps>  
  2.   
  3. @{  
  4.     ViewBag.Title = "GetEmploye";  
  5. }  
  6.   
  7. <h2>GetEmploye</h2>  
  8.   
  9. <p>  
  10.     @Html.ActionLink("Create New", "Create")  
  11. </p>  
  12. <table>  
  13.     <tr>  
  14.         <th>  
  15.             @Html.DisplayNameFor(model => model.Empname)  
  16.         </th>  
  17.         <th>  
  18.             @Html.DisplayNameFor(model => model.Empcity)  
  19.         </th>  
  20.         <th>  
  21.             @Html.DisplayNameFor(model => model.Empaddress)  
  22.         </th>  
  23.         <th></th>  
  24.     </tr>  
  25.   
  26. @foreach (var item in Model) {  
  27.     <tr>  
  28.         <td>  
  29.             @Html.DisplayFor(modelItem => item.Empname)  
  30.         </td>  
  31.         <td>  
  32.             @Html.DisplayFor(modelItem => item.Empcity)  
  33.         </td>  
  34.         <td>  
  35.             @Html.DisplayFor(modelItem => item.Empaddress)  
  36.         </td>  
  37.         <td>  
  38.             @Html.ActionLink("Edit", "Edit", new { id=item.Empid }) |  
  39.             @Html.ActionLink("Details", "Details", new { id=item.Empid }) |  
  40.             @*@Html.ActionLink("Delete", "Delete", new { id=item.Empid })*@  
  41.             <a onclick="return confirm('Are You Sure?');" href="@Url.Action("Delete", "Employe", new { id = item.Empid })">Delete</a>  
  42.   
  43.         </td>  
  44.     </tr>  
  45. }  
  46.   
  47. </table>  
The following is the output of the preceding code:



Edit Employe

We can create a view "Edit.cshtml" under the View/Employe folder that uses two action methods of the controller for the Get request and another for the Post request.
  1. @model Web.Models.Emps  
  2.   
  3. @{  
  4.     ViewBag.Title = "Edit";  
  5. }  
  6.   
  7. <h2>Edit</h2>  
  8.   
  9.   
  10. @using (Html.BeginForm()) {  
  11.     @Html.ValidationSummary(true)  
  12.   
  13.     <fieldset>  
  14.         <legend>Emps</legend>  
  15.   
  16.         <div class="editor-label">  
  17.             @Html.LabelFor(model => model.Empid)  
  18.         </div>  
  19.         <div class="editor-field">  
  20.             @Html.EditorFor(model => model.Empid)  
  21.             @Html.ValidationMessageFor(model => model.Empid)  
  22.         </div>  
  23.   
  24.         <div class="editor-label">  
  25.             @Html.LabelFor(model => model.Empname)  
  26.         </div>  
  27.         <div class="editor-field">  
  28.             @Html.EditorFor(model => model.Empname)  
  29.             @Html.ValidationMessageFor(model => model.Empname)  
  30.         </div>  
  31.   
  32.         <div class="editor-label">  
  33.             @Html.LabelFor(model => model.Empcity)  
  34.         </div>  
  35.         <div class="editor-field">  
  36.             @Html.EditorFor(model => model.Empcity)  
  37.             @Html.ValidationMessageFor(model => model.Empcity)  
  38.         </div>  
  39.   
  40.         <div class="editor-label">  
  41.             @Html.LabelFor(model => model.Empaddress)  
  42.         </div>  
  43.         <div class="editor-field">  
  44.             @Html.EditorFor(model => model.Empaddress)  
  45.             @Html.ValidationMessageFor(model => model.Empaddress)  
  46.         </div>  
  47.   
  48.         <p>  
  49.             <input type="submit" value="Save" />  
  50.         </p>  
  51.     </fieldset>  
  52. }  
  53.   
  54. <div>  
  55.     @Html.ActionLink("Back to List", "Index")  
  56. </div>  
  57.   
  58. @section Scripts {  
  59.     @Scripts.Render("~/bundles/jqueryval")  
  60. }  
The following is the output of the preceding code.



Details of employee

We can create a view "Detail.cshtml" under the View/Employe folder that uses one action method (Details) of the controller for the Get request.
  1. @model Web.Models.Emps  
  2.   
  3. @{  
  4.     ViewBag.Title = "Details";  
  5. }  
  6.   
  7. <h2>Details</h2>  
  8.   
  9. <fieldset>  
  10.     <legend>Emps</legend>  
  11.   
  12.     <div class="display-label">  
  13.          @Html.DisplayNameFor(model => model.Empid)  
  14.     </div>  
  15.     <div class="display-field">  
  16.         @Html.DisplayFor(model => model.Empid)  
  17.     </div>  
  18.   
  19.     <div class="display-label">  
  20.          @Html.DisplayNameFor(model => model.Empname)  
  21.     </div>  
  22.     <div class="display-field">  
  23.         @Html.DisplayFor(model => model.Empname)  
  24.     </div>  
  25.   
  26.     <div class="display-label">  
  27.          @Html.DisplayNameFor(model => model.Empcity)  
  28.     </div>  
  29.     <div class="display-field">  
  30.         @Html.DisplayFor(model => model.Empcity)  
  31.     </div>  
  32.   
  33.     <div class="display-label">  
  34.          @Html.DisplayNameFor(model => model.Empaddress)  
  35.     </div>  
  36.     <div class="display-field">  
  37.         @Html.DisplayFor(model => model.Empaddress)  
  38.     </div>  
  39. </fieldset>  
  40. <p>  
  41.     @Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |  
  42.     @Html.ActionLink("bacl to the list","Getcollegelist","Employe")  
  43. </p>  
The following is the output of the preceding code:



Delete Employe

If we click on the delete link then a confirmation window is opened. Click on the OK button then data will be deleted from the database.



Summary

In this article we learned about CRUD operations using the Repository pattern and how to consume the ASP.NET Web API using ASP.NET MVC4.

Up Next
    Ebook Download
    View all
    Learn
    View all