1.创建一个MVC项目,选择API

2.在Models层里添加Product类,IProductRepository接口,ProductRepository类

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类型

get 类型 用于从服务器端获取数据,且不应该对服务器端有任何操作和影响

post 类型 用于发送数据到服务器端,创建一条新的数据,对服务器端产生影响

put 类型 用于向服务器端更新一条数据,对服务器端产生影响 (也可创建一条新的数据但不推荐这样用)

delete 类型 用于删除一条数据,对服务器端产生影响

4.前端操作

---加载数据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'));
});
});
}

-----根据Id查找GET

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);
});
}

----添加数据POST

function add() {
//用于保存用户输入的数据

//添加一条记录,请求类型:post 请求url: /api/Products
//请求到ProductsController.cs中的 public HttpResponseMessage PostProduct(Product item) 方法
$("#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("添加成功");
$("#products").children("li").remove();//清除之前的子元素
load();//刷新
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("请求失败,消息:" + textStatus + " " + errorThrown);
}
});
});
}

---也是根据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; charset=urf-8",
success: function (data) {
$("#name2").val(data.Name);
$("#category2").val(data.Category);
$("#price2").val(data.Price);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("请求失败,消息:" + textStatus + " " + errorThrown);
}
});
});
}

------更新操作 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;charset=urf-8",
success: function () {
alert("修改成功");
$("#products").children("li").remove();//清除之前的子元素
load();//刷新
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("请求失败,消息:" + textStatus + " " + errorThrown);
}
})
});
}

-----删除操作 DELETE
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 + " 的记录删除成功!");
$("#products").children("li").remove();//清除之前的子元素
load();//刷新
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("请求失败,消息:" + textStatus + " " + errorThrown);
}
});
});
}

 

posted on 2016-06-17 08:25  linwenda  阅读(564)  评论(0编辑  收藏  举报