Web api using aps.net

 Before let's learn how browser communicate with web server.


Communication between Browser and Server




Http Request Life Cycle

1. Http Server waits for the request to come on Socket (Port = 80) 

2. Web Browser submits a request for a given URL after creating a Socket in local process. 

3. Request is submitted to DNS server so that based on domain name IP address is fetched. 

4. Browser now submits the request to Http Server. 

5. Server accepts the request and shifts the client to another Socket so that the socket on port 80 is released for receiving request from other clients. 

6. Now Browser and Server are connected to each other. 

7. Browser submits request as per HTTP protocol 

8. Server processes the request, renders the response and breaks the connection.

 

HTTP Protocol


 Its Application Protocol 

 The communication between web server and web browser on internet is done using HTTP protocol. 

 HTTP is a specification by Internet Engineering Task Force (IETF) and W3C. 

 HTTP Protocol is the safest protocol on internet. 

 HTTP communicates only in the String Format and is thus virus free and is platform independent. 

 HTTP protocol works on PULL technology. i.e. we can pull everything available on webserver but we cannot push content to the server unless server allows for it. 

 HTTP is a stateless protocol. This is because it doesn’t know whether the request that has been made is part of an ongoing correspondence or just a single message. 

 Latest Version is 1.1


HTTP Protocol Structure 

HTTP Request Structure (BrowserServer) 

1. Request Line. 

 2. Request Header. 

3. Message Body (Posted Data). 



HTTP Response Structure (ServerBrowser) 

1. Status Line. 

2. Response Headers. 

3. Message Body (Page Content).

HTTP looks like this: it sends the request, which looks like: 

GET Demo/default.htm HTTP/1.0 

Header1: bla 

Header2: blub 

{emptyline} 

N1=V2&N2=V2&N3=V3


Then the server responds like this:


 HTTP/1.1 200 OK 

Date: Mon, 23 May 2005 22:38:34 GMT 

Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux) 

Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT 

Etag: "3f80f-1b6-3e1cb03b" 

Accept-Ranges: none 

Content-Length: 438 

Connection: close 

Content-Type: text/html; 

charset=UTF-8




 Request Line: Method Path Protocol / Version 

Example: GET Demo/default.htm http/1.1 

 Request Header: These are the name value pairs submitted by the browser to the server .It contains the information about the browser and the OS on the client machine. 

 Message Body is the stream of name value pairs submitted to server when the form is submitted using the method POST.



CGI Environmental Variables: It’s a collection of name value pairs including request headers and information about the server in a context of a given request. The names of these variables are based on CGI (Common Gateway Interface) specification. These are also referred as Server Variables




Understanding Message Body

<form name="Form" action="demo.asp" method="post">
    <input type=".........
    <input type="submit" name="s1" value="Submit">
</form>

 

When the form is submitted by clicking on the submit button it submits the Name/ Value pair of every input element in the form to the server. 


About Get and Post Methods: 

GET Method: 

1. All the name value pairs are submitted as a query string. 

2. It’s not secured as it is visible in plain text format in the Location bar of the web browser. 

3. Length of the string is restricted. 

4. If method is not mentioned in the Form tag, this is the default method used. 

5. If get method is used and if the page is refreshed it would not prompt before the request is submitted again. 


POST Method: 

1. All the name value pairs are submitted in the Message Body of the request. 

2. Length of the string (amount of data submitted) is not restricted. 

3. Post Method is secured because Name-Value pairs cannot be seen in location bar of the web browser. 

4. If post method is used and if the page is refreshed it would prompt before the request is submitted again. Response Structure Status Line

Status Code Status Description
1xx Information
2xx Success
3xx Redirect
4xx File not found/not authored/ not authenticated
5xx Server Error

About Web Server: 

 Every web server has a default directory and by default on IIS it is: c:\inetpub\wwwroot\.

 Only content placed in this folder and its sub folder is accessible to clients on Internet. 

 From Browser: http://servername:PortNo/Directory/default.html 

What is IIS (Internet Information Server)? 

It is a windows component, a web server that accepts requests from client browsers and responds with the requested page(s) IIS Manager: A tool to configure and manage IIS. To launch IIS Manager one of the below methods can be used.

 Control Panel ==> Administrative Tools ==> IIS Manager 

(Or) 

Start ==> Run ==> inetmgr.exe 

Default Website: Default website is a website provided in IIS at the time of installation of IIS. The physical directory used by the default website of IIS is c:\inetpub\wwwroot and the port is 80



MVC
 MVC is a pattern which is used to split the application's implementation logic into three components i.e. models, views, and controllers



t is architecture for developing interactive applications where there would be a user interaction involved and event handling would occur

Model– It represents the application data domain. In other words applications business logic is contained within the model and is responsible for maintaining data .Model doesn't have reference to either view or controller. Only then it can be used by any controller and any view

View– It represents the user interface, with which the end users communicates. In short all the user interface logic is contained within the view. View can use any controller

Controller– It is the controller that answers to user actions. Based on the user actions, the respective controller responds with the model and choose a view to render that display the user interface. The user input logic is contained with-in the controller. View has reference to model. Contoller can either create model or might get a reference to model.

Role of Controller

 The controller responds to user interactions, with the application, by selecting the action method to execute and selecting the view to render. 


Advantage of MVC Framework
i. . Provides a clean separation of concerns between UI (Presentation layer), model (Transfer objects/Domain Objects/Entities) and Business Logic (Controller). 
II. Easy to UNIT Test. 
III. Improved reusability of views/model. One can have multiple views which can point to same model and vice versa. IV. Improved structuring of the code


We can use both MVC and webForms in the same project based on common ASP.NET framework and also share a  common instance for executing


What is a Model? 
1. MVC model is basically a C# or VB.NET class 
 2. A model is accessible by both controller and view 
3. A model can be used to pass data from Controller to View 
4. A view can use model to display data in page (HTML output). 

What is a View? 
 1. View is an CSHTML page without having a code behind file. 
2. All page specific HTML generation and formatting can be done inside view. 
3. One can use Inline code (server tags ) to develop dynamic pages. 
4. A request to view can be made only from a controller’s action method. 

What is a Controller? 
1. Controller is basically a C# or VB.NET class which inherits System.Web.Mvc.Controller 
2. Controller is a heart of the entire MVC architecture. 
3. Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views. 
 4. Controller can access and use model class to pass data to views . 

Core features of MVC framework are: 
I. Clear separation of application concerns (Presentation and Business Logic). 
II. It reduces complexity that makes it ideal for large scale applications where multiple teams are working. 
III. It’s an extensible as well as pluggable framework. We can plug components and further customize them easily. 
 IV. It provides extensive support for URL Routing that helps to make friendly URLs (means friendly for human as well as Search Engines). 
V. It supports for Test Driven Development (TDD) approach. In ASP.NET WebForms, testing support is dependent on Web Server but MVC makes it independent of Web Server, database or any other classes. 
VI. Support for existing ASP.NET features like membership and roles, authentication and authorization, provider model and caching etc.

Advantage of MVC over ASP.NET
I. Provides a clean separation of concerns among UI (Presentation layer), model (Transfer objects/Domain Objects/Entities) and Business Logic (Controller). 
II. Easy to UNIT Test. 
III. Improved reusability of model and views. We can have multiple views which can point to the same model and vice versa. 
IV. Improved structuring of the code. 
V. Integration with client side script is easy as Ids of elements are in control


Separation of concerns in MVC
s. It is the process of breaking the program into various distinct features which overlaps in functionality as little as possible. ASP.Net MVC pattern concerns on separating the content from presentation and data-processing from content

Unlike ASP.NET Web Forms, MVC doesn't have any server controls for forms. It instead uses HTML Helper class for achieving the same. As it doesn't have any controls, it doesn't depend on the Hidden Field View State unlike Web Forms


 Model: It manages data basically state of application in memory. There is no fixed size or shape of model objects since what we intent to hold in memory in one application may not be the same as that in other application. It includes all of an application’s validation logic, business logic and data access logic. For example, an Employee object (Model) might retrieve information from a database, operate on it, validate it and then write updated information back to an Employee table in database. 

 View: It contains logic for rendering Graphical Representation / HTML output. Typically it creates UI with data from Model. An example would be an edit view of a Products table that displays text boxes, dropdown lists, and check boxes based on the current state of a Products object. 

 Controller: It contains control flow logic. It is the one which interacts with both models and views to control the flow of application execution. The controller handles and responds to user input and interaction by creating and passing model to view. A controller can send commands to the model to update the model's state.

What is ASP.NET MVC framework?
A Framework is a collection of classes which provide abstraction of a particular concept. Framework classes are re-usable since a Framework is like a Semi-complete application which has to be extended and made complete for developing a specific application. Our code fits into the Framework through extension points. 
  Every Web Application is interactive by nature and hence is a potential candidate is applying MVC architecture. 
 ASP.NET MVC is an alternative framework to ASP.NET WebForm framework for developing Web based applications using ASP.NET Framework. 
  ASP.NET Versions: 
13 March 2009=== ASP.NET MVC 1 
10 March 2010 ===ASP.NET MVC 2 
13 January 2011=== ASP.NET MVC 3 
15 August 2012=== ASP.NET MVC 4 
30 May 2013=== ASP.NET MVC 4 4.0.30506.0 
17 October 2013=== ASP.NET MVC 5 
17 January 2014=== ASP.NET MVC 5.1 
10 February=== 2014 ASP.NET MVC 5.1.1 
4 April 2014=== ASP.NET MVC 5.1.2 
22 June 2014=== ASP.NET MVC 5.1.3 
1 July 2014 ===ASP.NET MVC 5.2.0 
28 August=== 2014 ASP.NET MVC 5.2.2 
9 January 2015=== ASP.NET MVC 5.2.3




What is a Model? 
1. MVC model is basically a C# or VB.NET class 
 2. A model is accessible by both controller and view 
3. A model can be used to pass data from Controller to View 
4. A view can use model to display data in page (HTML output). 

What is a View? 
1. View is an CSHTML page without having a code behind file. 
2. All page specific HTML generation and formatting can be done inside view. 
3. One can use Inline code (server tags ) to develop dynamic pages. 
4. A request to view can be made only from a controller’s action method. 

What is a Controller? 
1. Controller is basically a C# or VB.NET class which inherits System.Web.Mvc.Controller 
2. Controller is a heart of the entire MVC architecture. 
3. Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views. 
 4. Controller can access and use model class to pass data to views . 

Advantage  of MVC based web application
 Its light weight because it does not use view state or server-based forms or server controls. 
 It makes it easier to manage complexity by dividing an application into the model, the view, and the controller. 
 Separating the view from rest of the application logic enables changing of view (technology) in future without affecting the rest of the application. For example you might have views in Silverlight or HTML 5. 
 Each developer based on his expertise can work on different parts of the application without stepping on each other toes. For example, one developer can work on the view, a second developer can work on the controller logic, and a third developer can focus on the business logic in the model. 
 RESTful / User friendly Url’s and this enables SEO. 
 Clean HTML and easy integration with JavaScript and JQuery. 
 It doesn’t have renaming of ID’s as in WebForm framework. 
 It provides better support for test-driven development (TDD). This is because we can focus on one aspect at a time i.e. we can focus on view without worrying about business logic. 
 It’s created to support pattern based software development. 
 It works well for Web applications that are supported by large teams of developers and Web designers who need a high degree of control over the application behavior. Easy to maintain since we can clearly pin point what code to open in case there are any changes to be done


Advantage of ASP.NET web forms

 It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls. 
 It uses a Page Controller pattern that adds functionality to individual pages. 
 It uses view state on server-based forms, which can make managing state information easier. 
 It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development. 
 In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model. 
 ASP.NET Web Forms offers a much greater and more robust toolbox (web controls) whereas MVC offers a more primitive control set relying more on rich client-side controls via jQuery (Javascript). 
 It's been around since 2002 and there is an abundance of information with regards to questions, problems, etc. Offers more third-party control - need to consider your existing toolkits



MVC 6 is know as ASP.NET  vNext
Single programming model for asp.net mvc and asp.net web api
optimized for cloud computing
supporting side by side deployment of runtime and framework along with application
out of the box support for dependency injection
vNext is open source and supports running on multiple platforms including Linux and mac




First MVC application

Creating new ASP.NET MVC project
1. Open Visual Studio and go to File => New => Project=> Select Visual C# => Web => ASP.NET Web Application, 
Name the project as MyFirstMVCApp => Click OK, 
Visual Studio will set up a default project structure. 
2. Now try to run the application by pressing F5 (or by selecting debug => Start Debugging). 
3. Run the application to see the o/p of the HomeController and Index view which are automatically generated. 
4. Following is the list of folders created 
 a. Content 
b. Controllers 
c. Models 
d. Scripts 
e. Views 
f. Views/Shared 
Following is the list of files added 
g. Global.asax – It can have all the Global code shared between all the web pages of the application. 
h. Web.Config: It has all the configuration settings of the application. 
i. Packages.config: This file is managed by the NuGet infrastructure. It's used to track installed packages with their respective versions. It uses NuGet to track packages such as jQuery, EntityFramework, WebApi, Modernizr etc. 

Part 1: Adding the First Controller: 
5. The default project template includes a folder called Controllers. Right-click the Controllers folder and choose Add => Controller. Enter the name HomeController and then click Add. 
6. Replace the whole HomeController class with this 
public class HomeController : Controller 
 public string Index() 
 { 
 return "Hello, ASP.NET MVC"; 
 }
 } 
Controller: In ASP.NET MVC incoming requests are handled by controllers. 
 Controllers are just simple classes inherited from System.Web.Mvc.Controller 
 Each public method on a controller is known as an Action Method, which means you can invoke it from the Web via some URL. 
7. Now run the application by pressing ctrl + F5 and you can see output as a plain text Hello ASP.NET MVC. 

Note: ASP.NET MVC applications use the routing system. 
This infrastructure decides how URLs map onto particular controllers and actions. Under the default routing configuration, you could request any of the following URLs and it would be handled by the Index action on HomeController: 
• / 
• /Home 
• /Home/Index 
So, when a browser requests http://yoursite/ or http://yoursite/Home, it gets back the output from Home Controller’s Index method. The output right now is string Hello ASP.NET MVC. 

Part 2: Producing some HTML output using View: 
 8. Creating and Rendering a View: 
 To render a view from Index() method, first rewrite the method as follows: 

public ActionResult Index() 
{
 return View(); 

public ActionResult SayHello(string fname,string lname) 
 ViewBag.FirstName = fname; 
 ViewBag.LastName = lname; 
 return View(); 

9. To Add view: 
Right-click the action method (either on the Index() method name or somewhere inside the method body) and then choose Add View. This will lead to the pop-up window. 

10. Click Add. For the action method a new view file is created at ~/Views/Home/Index.cshtml. 

11. Replace generated markup content with below html in Index.cshtml Hello, ASP.NET MVC (from the view)! SayHello 

12. Add the following to Sayhello.cshtml

SayHello

Hello @(ViewBag.FirstName + " " + ViewBag.LastName) 13. Press CTRL + F5 to run the application again, and you should see your view template at work. Now, though, we are returning an object of type ViewResult, which instructs the MVC Framework to render a view. If we do not specify a view name, it picks the conventional one for this action method (i.e., ~/Views/Home/Index.aspx) 
 

<h2> say Hello </h2>
Hello @(ViewBag.FirstName + " " + ViewBag.LastName) 
13. Press CTRL + F5 to run the application again, and you should see your view template at work. Now, though, we are returning an object of type ViewResult, which instructs the MVC Framework to render a view. If we do not specify a view name, it picks the conventional one for this action method (i.e., ~/Views/Home/Index.aspx) 

Part 3: Initializing and Passing Model to View: 
14. Add Person class to Models folder 
namespace MyFirstMVCWebApp.Models 
{ public class Person 
 { 
 public string FirstName { get; set; } 
 public string LastName { get; set; } 
 } 
}
 15. Add the action method to HomeController as below 
public ActionResult SayHello(string fname,string lname) 
{
 Person p = new Person(); 
 p.FirstName = fname; 
 p.LastName = lname; 
 return View(p); 

16. Update SayHello.CSHTML as below
Hello @(Model.FirstName + " " + Model.LastName) 
17. Run the application to view the output of Http://localhost/Home/SayHello?fname=A&lname=B

understanding lifecyle of ASP.NET MVC request








Introduction to web API
 ASP.NET Web API is a framework for building and consuming HTTP services that can reach a broad range of clients including browsers, phones and tablets. 
  ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
 We can use either XML or JSON as output. JSON is good for mobile apps with slow connections, for example. You can call an API from jQuery and better utilize the client's machine and browser. 
 ASP.NET Web API takes the best features from WCF Web API and merges them with the best features from MVC. WCF needs lot of configurations, URI Templates, Contracts and endpoints. Service implementation and consumption is not simple.

Example: 
 1.Create a project using ASP.NET MVC Web Application temple 
 2. VS -> New Project -> ASP.NET MVC Web Application 
3. Web API is one of the built in project template. 
Click OK 
 Note: In this example 
a) ValuesController inherits ApiController and has some simple methods to returns some sample data. 
b) Edit App_Start/WebApiConfig.cs: 
Web API Routes: 
public static class WebApiConfig 
 public static void Register(HttpConfiguration config) 
 {
 config.MapHttpAttributeRoutes(); 
 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", 
//Note that action method name is missing 
 defaults: new { id = RouteParameter.Optional } ); 
 } 
4. Let’s just modify the methods to have better test data.
public class ValuesController : ApiController
 private static List list = new List { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; 
 // GET api/values 
 public IEnumerable GetList() 
 { 
 return list; 
 } 
 // GET api/values/3 
 public string GetItem(int id) 
 { 
 return list[id]; 
 } 
 // POST api/values 
 public List Post([FromBody]string value) 
 { 
 list.Add(value); return list; 
 } 
 // PUT api/values/5 
 public void Put(int id, [FromBody]string value) 
 { 
 list[id] = value; 
 } 
 // DELETE api/values/5 
 public void Delete(int id) 
 { 
 list.RemoveAt(id); 
 } 
} 


WEB API is REST Complaint, so it typically consists of Get(), Put(), Post(), Delete() methods
Method URL structure
Get() api/value
GetItem(int i) api/value/i
post(i) api/Values/i with Post method
delete(i) api/Values/i with Delete method.
put(i,value) api/values/i

Get==> get item or get all items
post ==> add tem
put ==> edit tem
merge ==> edit item
delete==> delete item

--> URL + HTTP method = map to method of APIController

difference between put and merge
put is used to update all property of existing object

merge is used to retain old value and update the extra data i.e. append

5. Testing in browser: Type the following URL in browser and view the output in both IE and FF. 
 http://localhost:2201/api/values/1 
 http://localhost:2201/api/values 
Note: The reason for the difference is that Internet Explorer and Firefox send different Accept headers, 
so the web API sends different content types in the response.

Calling the web AI with javascrit and jQuery

6. Add the following to Index View of Home Controller:

 All Items



<div>
    <div> All Items
    <ul id="items">

    </ul>

</div>
<input type="text" id="txtIndex" />
<input type="button" name="bthGetValue" value="Get Value" onclick="btnGetValue_click()" />
<input type="button" name="bthAddValue" value="Add Value" onclick="btnAddValue_click()" />
<input type="button" name="bthGetValue" value="Edit Value" onclick="btnEditValue_click()" />
<input type="button" name="bthDeleteValue" value="Delete at" onclick="btnDeleteValue_click()" />

<span id="spnValue"></span>

</div>
</div>

@secion scrpts
{

<script>
$(document).ready(function() {
getItems();

})

function getitems()
{
$.getJSON("/api/values/",
function (data){
$.each(data, function(key,val) {
$('#items').append("<li>"  +val + "</li>")
});
});
}

function btnGetValue_click()
{
var result=$.getJSON("api/values/"+$("#txtIndex").val(),
function(data){
$("#spnValue.text(data);

}
);
result.fail(function(err) {
alert("error fetching data")
})

}


function btnAddValue_click)
{
var value = $("#txtIndex").val();
$.ajax("/api/values/",
{
type:"Post",
data: "=" +value,
contentType: "application/x-www-form-urlencoded",
dataType: "JSON",
success: function (data) {
alert('Added');
$("#items").html("");
getItems();
}
});
}


function btnEditValue_click()
{
varvalue=$("#txtIndex').val();
$.ajax("/api/values/2",
{
type: "Put",
ddata: "=" + value,
contentType: "application/x-www-form-urlenoded",
dataType: "JSON",
success: function(data) {
alert('updated');
$("#item").html("");
gettems();
}
});


}
function btnDeleteValue_click() {
var index = $('#txtIndex').val(); 
 $.ajax("/api/values/" + index, 
 { 
type: "Delete", 
 contentType: "application/x-www-form-urlencoded", 
 dataType: "JSON", 
 success: function (data) 
 alert('Deleted'); 
 $("#items").html(""); 
 getItems(); \
 }); 
 }  


</script>
}

HttpResponseMessage and IHttpActionResult

A Web API controller action can return any of the following: 
1. void: Return empty 204 (No Content) 
2. HttpResponseMessage: Convert directly to an HTTP response message.

public HttpResponseMessage Get() 
{
 IEnumerable emps = GetEmployeesFromDB(); 
 // Write the list to the response body. 
 HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, emps); 
 return response; 
}

3. IHttpActionResult: Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message.

[ResponseType(typeof(Employee))] 
public IHttpActionResult GetEmployee(int id) 
 Employee employee = db.Employees.Find(id); 
 if (employee == null) 
 { 
 return NotFound(); 
// returns NotFoundResult 
 } 
 return Ok(employee); 
// returns System.Web.Http.Results.OkNegotiatedContentResult 
}

4. Some other type: Write the serialized return value into the response body; return 200 (OK). 
 A disadvantage of this approach is that you cannot directly return an error code, such as 404. However, you can throw an HttpResponseException for error codes. 
 Web API uses the Accept header in the request to choose the formatter


Creating a Web API that Supports CRUD Operations using EF
1. Create a MVC project with Web API template 
 2. Add ADO.NET Entity Data Model 
3. Add Employee Table to DemoDb.Edmx file. 
4. Add controller EmployeesController, Template= API Controller with read/write actions, using Entity Framework . 
5. Add the following to EmployeesController. 


public EmployeesController() 
 var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 


Following are the list of methods which are auto generated: 
a) To Get all Employees 
// GET api/Employees 
IQueryable GetEmployees() 
The method name starts with "Get", so by convention it maps to GET requests. Also, because the method has no parameters, it maps to a URI that does not contain an "id" segment in the path. 

b) To Get details of particular employee 
// GET api/Employees/5 
[ResponseType(typeof(Employee))] 
IHttpActionResult GetEmployee(int id) 

This method name also starts with "Get", but the method has a parameter named id. This parameter is mapped to the "id" segment of the URI path. The ASP.NET Web API framework automatically converts the ID to the correct data type (int) for the parameter.

 c) To Add a new Employee 
// POST api/Emp 
[ResponseType(typeof(Employee))] 
IHttpActionResult PostEmployee(Employee employee) 

To handle POST requests, we define a method whose name starts with "Post...". The method takes a parameter of type Employee. By default, parameters with complex types are deserialized from the request body. Therefore, we expect the client to send us a serialized representation of an employee object, using either XML or JSON for the serialization. 

d) To update an Employee 
// PUT api/Emp/5 
[ResponseType(typeof(void))] 
IHttpActionResult PutEmployee(int id, Employee employee) 
The method name starts with "Put...", so Web API matches it to PUT requests. The method takes two parameters, the Emp ID and the updated employee. The id parameter is taken from the URI path, and the employee parameter is deserialized from the request body. By default, the ASP.NET Web API framework takes simple parameter types from the route and complex types from the request body. 

e) To Delete an Employee 
// DELETE api/Emp/5 
IHttpActionResult DeleteEmployee(int id) 

6. Add the following to Index View of Home Controller

<h1>Add Employee</h1>
<div>
<label for="name"> Name: </label>
<input type="text" id="name" />
<label for="salary"> Salary: </label>
<input type="text" id="salary" />
<label for="ateOfJoin">ateOfJoin:</label>
<iput type="button" value="Add Employee" onclick="AddEmployee();"/>
</div>
</div>


@section scrits
{
<script type="text/javascrit">
$(document).ready(function() {
GetAllEmloyees()
});
function GetAllEmployees() {
$.getJSON('/api/Employee/",
function(data)
{
//on success data contains a list of employee
$("#items").text("");
$.each(data, function (key, emp) 
 // Format the text to display. 
 var str = emp.EmpId + ", " + emp.EmpName + ", " + emp.Salary + ", " + emp.IsActive; 
 // Add a list item. 
 $('<li/>', { text: str }).appendTo($('#items')); 
 }); 
 }); 
 }

function GetEmployeeDetails() 
 var id = $('#empid').val(); 
 $.getJSON("/api/Employee/" + id, function (emp) 
 var str = emp.EmpId + ", " + emp.EmpName + ", " + emp.Salary + ", " + emp.IsActive; 
 $('#item').text(str); 
 }) 
 } 
function AddEmployee() 
{
 $.ajax("/api/Employees",
type: "POST", 
 contentType: "application/json;charset=utf-8", 
 data: JSON.stringify 
 ({ 
 EmpId: 0, 
 EmpName: $("#name").val(), 
 Salary: $("#salary").val(), 
 DateOfJoin: $("#dateOfJoin").val(), 
 IsActive: true, DeptId: 1 
 }),
 dataType: "json", 
 success: function (data) 
 GetAllEmployees(); 
 } 
 }); 
 } 

 function DeleteEmployee() 
{ var id = $('#empid').val(); 
 $.ajax({ 
 type: "DELETE", 
 contentType: "application/json;charset=utf-8", 
 url: "/api/Employee/" + id, 
 dataType: "json", 
 success: function (data) 
 GetAllEmployees(); 
 } 
 }); 
 }   
</script>
}




Comments