HTML and CSS Reference
In-Depth Information
Get(id) : Represents an HTTP GET request and SELECT is a single data item that is to be
returned to the caller based on the ID specified.
Post() : Represents an HTTP POST request and is used to INSERT a data item into a
database.
Put(id) : Represents an HTTP PUT request and is used to UPDATE a data item from the
database matching the specified ID.
Delete(id) : Represents an HTTP DELETE request and is used to DELETE a data item
from the database.
Note that though this example needs CRUD functionality, it isn't necessary that the Web API and
XMLHttpRequest be used exclusively for such scenarios. Listing 11-8 shows the Get() and Post() methods of
CustomerController .
Listing 11-8. Get() and Post() Methods of the CustomerController Class
public class CustomerController : ApiController
{
public IEnumerable<Customer> Get()
{
NorthwindEntities db = new NorthwindEntities();
var data = from item in db.Customers
orderby item.CustomerID
select item;
return data;
}
public void Post(Customer obj)
{
NorthwindEntities db = new NorthwindEntities();
db.Customers.AddObject(obj);
db.SaveChanges();
}
}
The Get() method returns an IEnumerable of Customer items. Inside, Get() selects all the Customer
items and returns them to the caller after sorting them based on the CustomerID column.
The Post() method accepts a Customer object as a parameter. This parameter comes from the jQuery
code you writer later. Post() adds the supplied Customer object to the Customers table using the
AddObject() method. To persist the data back to the database, you call SaveChanges() .
To successfully call a Web API from the client, you also need to add the following routing information
in the Global.asax file:
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
name: “DefaultApi”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
}
 
Search WWH ::




Custom Search