Posts Tagged ‘MVC 4’

Web API : ASP.NET has introduced a new concept of building Web API on top of .NET Framework and as we all know HTTP services has a vast market in terms of clients including browsers, mobile phones or any desktop application, in this blog we are going to talk a bit about what ASP.NET WebAPI is all about and how to make one and consume one:

First you would need the following:

  1. Visual Studio 2011 or Visual Studio 2010 with SP1
  2. ASP.NET MVC 4 (how to get that is mentioned Below)

Steps to get MVC 4 and Web API:

    1. Go and download ASP.NET MVC 4 from ( http://go.microsoft.com/fwlink/?LinkId=243392 )
    2. Once Downloaded and Installed you will see following Template installed in your New Project Dialog box:

MVC 4 Project Template

  1. After you select your project MVC 4 you will get New ASP.NET MVC 4 Project Dialog from there choose “Web API” type project:

    Web API Dialog

    Web API Dialog

Create a New Model:

A model is nothing but an object to represent data in your project. A model is automatically serialized by ASP.NET web API into JSON or XML or any other format that can be read by a client (Browser or phone or any other client). So first to see how Web API works we will add a new Model by adding a new class to Models folder in your solution explorer:

Add a Model

Add a Model

Give some meaningful name to your model for example “Employee” and set some properties like EmployeeID, Name etc :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebAPI.Models
{
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }        
    }
}

Adding a New Controller:

A Controller is nothing but an object that a Client Calls using HTTP requests, By default when you create a MVC 4 project there will be two controllers created already “HomeController” and “ValueController”, if you are familiar with MVC 3 then you know HomeController is meant to serve HTML pages for application or site where as the “ValueController” is a sample WebAPI controller created by MVC 4 Project template for reference and inherits the ApiController class, we will leave this as it is and create a New Controller of type API in the Controllers folder by right clicking and adding a new Empty API Controller and name is “EmployeeController”:

Add a Controller

Add a Controller

Empty API Controller

Empty API Controller

Once added add using Statement to call your Models in EmployeeController:

using WebAPI.Models;

And add the following code to return a default list of Employee and a Controller Method to search your list as given below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    public class EmployeeController : ApiController
    {
      public IEnumerable<Employee> GetAllEmployees()
      {
          return new List<Employee>
          {
              new Employee() { EmployeeID = 1, EmployeeName = "brainz 1"},
              new Employee() { EmployeeID = 2, EmployeeName = "brainz 2"},
              new Employee() { EmployeeID = 3, EmployeeName = "brainz 3"}
          };
      }

        public Employee GetEmployeeById(int id)
        {
            if (id < 1 || id > 3)
            {
                throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
            }
            return new Employee() { EmployeeID = id, EmployeeName="brainz "+ id.ToString() };
        }
    }
}

The GetAllEmployee Method would return list of employee and GetEmployeeById will return the employee with matching ID,else httpResponseException will be thrown(this is nothing but a 404 Error), once done compile this and your Web API is ready to be used and consumed.

Calling the API using JQuery or JavaScript:

Go to View by Expanding the Views folder and open Index.cshtml file, and remove everything by the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>ASP.NET Web API</title>
    <script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>   
</head>
<body>
    <div>
        <h1>All Employees</h1>
        <ul id='employee' />
    </div>
    <div>
        <label for="EmployeeID">ID:</label>
        <input type="text" id="EmployeeID" size="5"/>
        <input type="button" value="Search" onclick="find();" />
        <p id="Employee" />
    </div>
</body>
</html>

Once done let’s call a HTTP GET Request to request the api: api/employee, using the getJSON function by making an Ajax Call:

<script type="text/javascript">
        $(document).ready(function () {
            // Send an AJAX request
            $.getJSON("api/employee/",
            function (data) {
                // On success, 'data' contains a list of employees.
                $.each(data, function (key, val) {                    
                    // Format the text to display.
                    var str = val.EmployeeID + ': ' + val.EmployeeName;

                    // Add a list item for the Employee.
                    $('<li/>', { html: str }).appendTo($('#employee'));
                });
            });
        });

    </script>

The final index.cshtml would look like :

<!DOCTYPE html>
<html lang="en">
<head>
    <title>ASP.NET Web API</title>
    <script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            // Send an AJAX request
            $.getJSON("api/employee/",
            function (data) {
                // On success, 'data' contains a list of employees.
                $.each(data, function (key, val) {                    
                    // Format the text to display.
                    var str = val.EmployeeID + ': ' + val.EmployeeName;

                    // Add a list item for the Employee.
                    $('<li/>', { html: str }).appendTo($('#employee'));
                });
            });
        });

        function find() {
            var id = $('#EmployeeID').val();
            $.getJSON("api/employee/" + id,
        function (data) {
            var str = data.EmployeeID + ': ' + data.EmployeeName;
            $('#employee').html(str);
        })
    .fail(
        function (jqXHR, textStatus, err) {
            $('#employee').html('Error: ' + err);
        });
        }        
    </script>
</head>
<body>
    <div>
        <h1>All Employees</h1>
        <ul id='employee' />
    </div>
    <div>
        <label for="EmployeeID">ID:</label>
        <input type="text" id="EmployeeID" size="5"/>
        <input type="button" value="Search" onclick="find();" />
        <p id="Employee" />
    </div>
</body>
</html>

Once this is done run your application to see the result and don’t forget to put your comments if any

Output

Output

Note: CSHTML page usually uses Razor but we have used simple HTML in our case.

Advertisements