Wednesday, 3 August 2016

Calling WebApi from MVC layer

In this Project you will be able to learn how you can call Web Api functions from MVC Layer project.

Follow the Steps:

1- First Create a new MVC4 Project.
2- In the same solution add a Web Api Project.


3- In the API Project, Add a Employee Model in Model Folder.

 public class EmployeeModel  
   {  
     public int EmpId { get; set; }  
     public string Name { get; set; }  
     public string Address { get; set; }  
   }  

4- In the Values API Controller Replace this function to get Employee data.

   public class ValuesController : ApiController  
   {  
     // GET api/values  
     public IEnumerable<EmployeeModel> Get()  
     {  
       List<EmployeeModel> list = new List<EmployeeModel>();  
       for (int i = 0; i < 10; i++)  
       {  
         EmployeeModel emp = new EmployeeModel();  
         emp.EmpId = i;  
         emp.Name = "Emp" + i;  
         emp.Address = "Delhi" + i;  
         list.Add(emp);  
       }  
       return list;  
     }  
   }  

5- Now Run the Web Api Project.


6- Now come to your MVC Project. Add this key in Web.config file.
<add key="baseurl" value="http://localhost:6763" />

Above Key contains the base url of Web Api.

7- In the Home Controller,  Add the Below Code.

     string apiUrl = ConfigurationManager.AppSettings["baseurl"]+"/api/Values/";  
     HttpClient client;  
     public HomeController()  
     {  
       client = new HttpClient();  
       client.BaseAddress = new Uri(apiUrl);  
       client.DefaultRequestHeaders.Accept.Clear();  
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
     }  

The above Code is required for getting data from Web Api.

8- In the MVC Project, Add a Employee Model in Model Folder.

 public class EmployeeModel  
   {  
     public int EmpId { get; set; }  
     public string Name { get; set; }  
     public string Address { get; set; }  
   }  


9- Now we will write the Code to fetch data from Web Api. For this I am using Index Action method in Home Controller.

  //  
     // GET: /Home/  
     public async Task<ActionResult> Index()  
     {  
       List<EmployeeModel> emp = new List<EmployeeModel>();  
       HttpResponseMessage responseMessage = await client.GetAsync(apiUrl);  
       if (responseMessage.IsSuccessStatusCode)  
       {  
         var responseData = responseMessage.Content.ReadAsStringAsync().Result;  
         emp = JsonConvert.DeserializeObject<List<EmployeeModel>>(responseData);  
       }  
       return View(emp);  
     }  

10- Add/Replace Index View.

 @model IEnumerable<WebApiWithMVC.Models.EmployeeModel>  
 @{  
   ViewBag.Title = "Index";  
 }  
 <h2>Index</h2>  
 <p>  
   @Html.ActionLink("Create New", "Create")  
 </p>  
 <table>  
   <tr>  
     <th>  
       @Html.DisplayNameFor(model => model.EmpId)  
     </th>  
     <th>  
       @Html.DisplayNameFor(model => model.Name)  
     </th>  
     <th>  
       @Html.DisplayNameFor(model => model.Address)  
     </th>  
     <th></th>  
   </tr>  
 @foreach (var item in Model) {  
   <tr>  
     <td>  
       @Html.DisplayFor(modelItem => item.EmpId)  
     </td>  
     <td>  
       @Html.DisplayFor(modelItem => item.Name)  
     </td>  
     <td>  
       @Html.DisplayFor(modelItem => item.Address)  
     </td>  
   </tr>  
 }  
 </table>  

11- Now Debug your Mvc Project. But before running Mvc project make sure your Web Api is running.




12- Please do not forget to share with your techie friends. You can download the complete project here Download

0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)