A preliminary understanding of Webapi (curd)

Source: Internet
Author: User

1. Create an MVC project and select the API

2. Add product class, Iproductrepository interface, Productrepository class in 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.39M});
ADD (new Product {Name = "yo-yo", Category = "Toys", Price = 3.75M});
ADD (new Product {Name = "Hammer", Category = "Hardware", Price = 16.99M});
}
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,delete type

Get types are used to fetch data from the server side and should not have any operational and impact on the server side

The post type is used to send data to the server side, creating a new data that has an impact on the server side

The put type is used to update a piece of data to the server side, which has an impact on the server side (a new data can also be created but not recommended)

The delete type is used to delete a piece of data that has an impact on the server side

4. Front-end operation

---loading data get

function Load () {

Send an AJAX request
$.getjson ("/api/products/",
function (data) {
On success, the ' 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 '));
});
});
}

-----Find 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 data entered by the user

Add a record, request type: Post request URL:/api/products
Request to 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 ("Add success");
$ ("#products"). Children ("Li"). Remove ();//Clear Previous child elements
Load ();//Refresh
},
Error:function (XMLHttpRequest, Textstatus, Errorthrown) {
Alert ("Request failed, message:" + Textstatus + "" + Errorthrown);
}
});
});
}

---also query data by ID

Function Show () {
$ ("#showItem"). Click (function () {
var inputID = $ ("#id2"). Val ();
$ ("#name2"). Val (""); br> $ ("#category2"). Val ("");
$ ("#price2"). Val ("");
$.ajax ({
URL: "/api/products/" + inputID,
Type: "GET",
ContentType: "Application/json; Charset=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 + "+ errorthr Own);
}
});
});
}

------Update action PUT
Function edit () {
$ ("# EditItem "). Click (function () {
var inputID = $ (" #id2 "). Val ();
var newproduct = Product.create ();
NEWPRODUCT.N Ame = $ ("#name2"). Val ();
Newproduct.category = $ ("#category2"). Val ();
Newproduct.price = $ ("#price2"). Val ();
$.ajax ({
URL: "/api/products/" + inputID,
Type: "PUT",
Data:JSON.stringify (newproduct),
ContentType: "Application/json;charset=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; Charset=uft-8 ",
Success:function (data) {
Alert ("id" + inputid + "record deleted successfully!) ");
$ ("#products"). Children ("Li"). Remove ();//Clear Previous child elements
Load ();//Refresh
},
Error:function (XMLHttpRequest, Textstatus, Errorthrown) {
Alert ("Request failed, message:" + Textstatus + "" + Errorthrown);
}
});
});
}

A preliminary understanding of Webapi (curd)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.