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

WebAPI的初步认识(CURD)的更多相关文章

  1. 将WebApi Host到控制台和IIS

    近期学习WebApi,初步感想是用起来很容易上手,概念上也很好理解,唯一不爽的地方就在于如果在Visual Studio环境里建立Webapi程序,它会自动给创建很多文件夹和文件,其中很多都是用不到的 ...

  2. 自行实现高性能MVC WebAPI

    wcf虽然功能多.扩展性强但是也面临配置忒多,而且restful的功能相当怪异,并且目前没法移植.asp.net core虽然支持webapi,但是功能也相对繁多.配置复杂.就没有一个能让码农们安安心 ...

  3. WebAPI学习及Swagger使用

    本文用来保存自己学习WebAPI和Swagger使用过程中参考的文章,以及对WebAPI的初步了解. 1.RESTful风格 WebAPI只支持Http协议: 1.1.WebAPI与MVC的区别 Va ...

  4. 线程安全使用(四) [.NET] 简单接入微信公众号开发:实现自动回复 [C#]C#中字符串的操作 自行实现比dotcore/dotnet更方便更高性能的对象二进制序列化 自已动手做高性能消息队列 自行实现高性能MVC WebAPI 面试题随笔 字符串反转

    线程安全使用(四)   这是时隔多年第四篇,主要是因为身在东软受内网限制,好多文章就只好发到东软内部网站,懒的发到外面,现在一点点把在东软写的文章给转移出来. 这里主要讲解下CancellationT ...

  5. 自行实现高性能MVC

    wcf虽然功能多.扩展性强但是也面临配置忒多,而且restful的功能相当怪异,并且目前没法移植.asp.net core虽然支持webapi,但是功能也相对繁多.配置复杂.就没有一个能让码农们安安心 ...

  6. ASP.NET Web API 2系列(四):基于JWT的token身份认证方案

    1.引言 通过前边的系列教程,我们可以掌握WebAPI的初步运用,但是此时的API接口任何人都可以访问,这显然不是我们想要的,这时就需要控制对它的访问,也就是WebAPI的权限验证.验证方式非常多,本 ...

  7. ASP.Net MVC开发基础学习笔记:五、区域、模板页与WebAPI初步

    一.区域—麻雀虽小,五脏俱全的迷你MVC项目 1.1 Area的兴起 为了方便大规模网站中的管理大量文件,在ASP.NET MVC 2.0版本中引入了一个新概念—区域(Area). 在项目上右击创建新 ...

  8. ASP.Net MVC开发基础学习笔记(5):区域、模板页与WebAPI初步

    一.区域—麻雀虽小,五脏俱全的迷你MVC项目 1.1 Area的兴起 为了方便大规模网站中的管理大量文件,在ASP.NET MVC 2.0版本中引入了一个新概念—区域(Area). 在项目上右击创建新 ...

  9. ASP.NET WEBAPI 简单CURD综合测试(asp.net MVC,json.net,sql基础存储过程和视图,sqlhelper,json解析)

    草图   真正的后端是不管前端是什么平台,用什么语言的,JSON格式的数据应该可以应对.用ASP.NET WEBAPI尝试做一个后端,实现最基本的CURD,业务逻辑和数据库操作都放在后端,前端只需要正 ...

随机推荐

  1. 在vivado中使用attribute

    之前最常用的一个attribute就是mark_debug了,语法如下:(*mark_debug="ture"*). 今天又学到几个新的,原文在这里:http://china.xi ...

  2. Vuejs使用笔记 --- component内部实现

    现在来系统地学习一下Vue(参考vue.js官方文档): Vue.js是一个构建数据驱动的web界面的库,其目标是实现响应的数据绑定和组合的试图组件. Vue.js拥抱数据驱动的视图概念,这意味着我们 ...

  3. 将字母变为其下个字母(abc变为bcd)

    题目描述 输入一行电报文字,将字母变成其下一字母(如'a'变成'b'--'z'变成'a'其它字符不变). 输入 一行字符 输出 加密处理后的字符 样例输入 a b 样例输出 b c#include & ...

  4. CSV表格读取

    读取CSV表格需要CSV表格的编码格式为UTF-8 ,这个脚本中有些是为了方便使用封装的dll 不过都是一些简单的实现,自己实现也很容易,可做参考. /// <summary> /// 构 ...

  5. Gridview实现删除弹出提示信息

    实现方法: 双击GridView的OnRowDataBound事件: 在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:       protected void ...

  6. isMemberOfClass和isKindOfClass的区别

    1.isMemberOfClass:作用:用于判断一个对象是否属于当前这个类   Person *rose = [[Person alloc] init];          if ([rose is ...

  7. C#pdf 切割成图片

    引用 using Ghostscript.NET;using Ghostscript.NET.Rasterizer; 需要安装 exe文件 public static GhostscriptVersi ...

  8. js判断页面是pc打开还是手机打开

    <script type="text/javascript"> function browserRedirect() { var sUserAgent = naviga ...

  9. springmvc 中controller与jsp传值

    参考:springmvc 中controller与jsp传值 springMVC:将controller中数据传递到jsp页面 jsp中,死活拿不到controller中的变量. 花了半天,网上列出各 ...

  10. 使用Gogs搭建Git服务器

    Git现在基本上已经代替SVN成为主流的源码管理工具了,我在之前的文章使用GIT进行源码管理--GIT托管服务中介绍过一些国内外的主流在线Git服务,虽然这些在线的Git服务大多非常好用,但是有的时候 ...