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

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives