WebAPI preliminary understanding (CURD), webapi understanding curd
1. Create an MVC project and select API
2. Add the Product class, IProductRepository interface, and ProductRepository class to the Models layer.
Public class Product
{
Public int ID {get; set ;}
Public string Name {get; set ;}
Public string Category {get; set ;}
Public decimal Price {get; set ;}
}
Public interface IProductRepository
{
IEnumerable <Product> GetAll ();
Product Get (int id );
Product Add (Product item );
Void Remove (int id );
Bool Update (Product item );
}
Public class ProductRepository: IProductRepository
{
Private List <Product> products = new List <Product> ();
Private int _ nextId = 1;
Public ProductRepository ()
{
Add (new Product {Name = "Tomato soup", Category = "Groceries", Price = 1.39 M });
Add (new Product {Name = "Yo-yo", Category = "Toys", Price = 3.75 M });
Add (new Product {Name = "Hammer", Category = "Hardware", Price = 16.99 M });
}
Public IEnumerable <Product> GetAll ()
{
Return products;
}
Public Product Get (int id)
{
Return products. Find (p => p. ID = id );
}
Public Product Add (Product item)
{
If (item = null)
{
Throw new ArgumentNullException ("item ");
}
Item. ID = _ nextId ++;
Products. Add (item );
Return item;
}
Public void Remove (int id)
{
Products. RemoveAll (p => p. ID = id );
}
Public bool Update (Product item)
{
If (item = null)
{
Throw new ArgumentNullException ("item ");
}
Int index = products. FindIndex (p => p. ID = item. ID );
If (index =-1)
{
Return false;
}
Products. RemoveAt (index );
Products. Add (item );
Return true;
}
}
3. get, post, put, and delete types
The get type is used to obtain data from the server without any operation or impact on the server.
The post type is used to send data to the server and create a new data, which has an impact on the server.
The put type is used to update a piece of data to the server, which has an impact on the server (you can also create a new data, but this is not recommended)
The delete type is used to delete a piece of data, which affects the server.
4. frontend operations
--- Load data GET
Function load (){
// Send an AJAX request
$. GetJSON ("/api/products /",
Function (data ){
// On success, 'data' contains a list of products.
$. Each (data, function (key, val ){
// Format the text to display.
Var str = val. Name + ': $' + val. Price;
// Add a list item for the product.
$ ('<Li/>', {text: str })
. AppendTo ($ ('# products '));
});
});
}
----- Search for GET by Id
Function find (){
Var id = $ ('# prodId'). val ();
$. GetJSON ("/api/products/" + id,
Function (data ){
Var str = data. Name + ': $' + data. Price;
$ ('# Product'). text (str );
})
. Fail (
Function (jqXHR, textStatus, err ){
$ ('# Product'). text ('error:' + err );
});
}
---- Add data POST
Function add (){
// Used to save user input data
// Add a record. Request type: post request url:/api/Products
// Request the public HttpResponseMessage PostProduct (Product item) method in ProductsController. cs
$ ("# AddItem"). click (function (){
Var newProduct = Product. create ();
NewProduct. Name = $ ("# name"). val ();
NewProduct. Category = $ ("# category"). val ();
NewProduct. Price = $ ("# price"). val ();
$. Ajax ({
Url: "/api/Products ",
Type: "POST ",
ContentType: "application/json; charset = UTF-8 ",
Data: JSON. stringify (newProduct ),
Success: function (){
Alert ("added successfully ");
$ ("# Products"). children ("li"). remove (); // clear the previous child element
Load (); // refresh
},
Error: function (XMLHttpRequest, textStatus, errorThrown ){
Alert ("request failed, message:" + textStatus + "" + errorThrown );
}
});
});
}
--- Query data by ID
Function show (){
$ ("# ShowItem"). click (function (){
Var inputId = $ ("# id2"). val ();
$ ("# Name2"). val ("");
$ ("# Category2"). val ("");
$ ("# Price2"). val ("");
$. Ajax ({
Url: "/api/Products/" + inputId,
Type: "GET ",
ContentType: "application/json; charsets = urf-8 ",
Success: function (data ){
$ ("# Name2"). val (data. Name );
$ ("# Category2"). val (data. Category );
$ ("# Price2"). val (data. Price );
},
Error: function (XMLHttpRequest, textStatus, errorThrown ){
Alert ("request failed, message:" + textStatus + "" + errorThrown );
}
});
});
}
------ Update operation PUT
Function edit (){
$ ("# EditItem"). click (function (){
Var inputId = $ ("# id2"). val ();
Var newProduct = Product. create ();
NewProduct. Name = $ ("# name2"). val ();
NewProduct. Category = $ ("# category2"). val ();
NewProduct. Price = $ ("# price2"). val ();
$. Ajax ({
Url: "/api/Products/" + inputId,
Type: "PUT ",
Data: JSON. stringify (newProduct ),
ContentType: "application/json; charsets = urf-8 ",
Success: function (){
Alert ("modified successfully ");
$ ("# Products"). children ("li"). remove (); // clear the previous child element
Load (); // refresh
},
Error: function (XMLHttpRequest, textStatus, errorThrown ){
Alert ("request failed, message:" + textStatus + "" + errorThrown );
}
})
});
}
----- DELETE operation
Function del (){
$ ("# RemoveItem"). click (function (){
Var inputId = $ ("# id2"). val ();
$. Ajax ({
Url: "/api/Products/" + inputId,
Type: "DELETE ",
ContentType: "application/json; charsets = uft-8 ",
Success: function (data ){
Alert ("+ inputId +" is deleted successfully! ");
$ ("# Products"). children ("li"). remove (); // clear the previous child element
Load (); // refresh
},
Error: function (XMLHttpRequest, textStatus, errorThrown ){
Alert ("request failed, message:" + textStatus + "" + errorThrown );
}
});
});
}