WebAPI的初步认识(CURD)
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)的更多相关文章
- 将WebApi Host到控制台和IIS
近期学习WebApi,初步感想是用起来很容易上手,概念上也很好理解,唯一不爽的地方就在于如果在Visual Studio环境里建立Webapi程序,它会自动给创建很多文件夹和文件,其中很多都是用不到的 ...
- 自行实现高性能MVC WebAPI
wcf虽然功能多.扩展性强但是也面临配置忒多,而且restful的功能相当怪异,并且目前没法移植.asp.net core虽然支持webapi,但是功能也相对繁多.配置复杂.就没有一个能让码农们安安心 ...
- WebAPI学习及Swagger使用
本文用来保存自己学习WebAPI和Swagger使用过程中参考的文章,以及对WebAPI的初步了解. 1.RESTful风格 WebAPI只支持Http协议: 1.1.WebAPI与MVC的区别 Va ...
- 线程安全使用(四) [.NET] 简单接入微信公众号开发:实现自动回复 [C#]C#中字符串的操作 自行实现比dotcore/dotnet更方便更高性能的对象二进制序列化 自已动手做高性能消息队列 自行实现高性能MVC WebAPI 面试题随笔 字符串反转
线程安全使用(四) 这是时隔多年第四篇,主要是因为身在东软受内网限制,好多文章就只好发到东软内部网站,懒的发到外面,现在一点点把在东软写的文章给转移出来. 这里主要讲解下CancellationT ...
- 自行实现高性能MVC
wcf虽然功能多.扩展性强但是也面临配置忒多,而且restful的功能相当怪异,并且目前没法移植.asp.net core虽然支持webapi,但是功能也相对繁多.配置复杂.就没有一个能让码农们安安心 ...
- ASP.NET Web API 2系列(四):基于JWT的token身份认证方案
1.引言 通过前边的系列教程,我们可以掌握WebAPI的初步运用,但是此时的API接口任何人都可以访问,这显然不是我们想要的,这时就需要控制对它的访问,也就是WebAPI的权限验证.验证方式非常多,本 ...
- ASP.Net MVC开发基础学习笔记:五、区域、模板页与WebAPI初步
一.区域—麻雀虽小,五脏俱全的迷你MVC项目 1.1 Area的兴起 为了方便大规模网站中的管理大量文件,在ASP.NET MVC 2.0版本中引入了一个新概念—区域(Area). 在项目上右击创建新 ...
- ASP.Net MVC开发基础学习笔记(5):区域、模板页与WebAPI初步
一.区域—麻雀虽小,五脏俱全的迷你MVC项目 1.1 Area的兴起 为了方便大规模网站中的管理大量文件,在ASP.NET MVC 2.0版本中引入了一个新概念—区域(Area). 在项目上右击创建新 ...
- ASP.NET WEBAPI 简单CURD综合测试(asp.net MVC,json.net,sql基础存储过程和视图,sqlhelper,json解析)
草图 真正的后端是不管前端是什么平台,用什么语言的,JSON格式的数据应该可以应对.用ASP.NET WEBAPI尝试做一个后端,实现最基本的CURD,业务逻辑和数据库操作都放在后端,前端只需要正 ...
随机推荐
- Find out files transfered via Bluetooth
The case was about business secret and forensic guy did a physical acquisition from a smart phone. H ...
- android开发--下载图片
1.背景介绍 网络上图片的请求,是我们最常见的网络请求之一,不亚于对json/xml数据的请求.一般要展示给用户看的,都不会是纯粹的文字,往往都是图文信息.而在移动互联网时代,图文又往往需要最新的资讯 ...
- Welcome to China
subway, railway, highway ,way way to dieofficer,announcer, professor, sir sir to lieWelcome to China
- prop和attr的区别
在高版本的jquery引入prop方法后,什么时候该用prop?什么时候用attr?它们两个之间有什么区别?这些问题就出现了. 对于HTML元素本身就带有的固有属性,在处理时,使用prop方法. 对于 ...
- 总结一些关于操作数据库是sql语句还是存储过程问题
总结一些关于操作数据库是sql语句还是存储过程问题 程序中,你跟数据的交互,需要向数据库拿数据.更改数据库的数据等,这些操作,本身不是程序完成的,而是程序发命令给数据库去做的,不管是通过sql语句方式 ...
- Redis的介绍和常用数据类型结构命令的总结
我们先来看一下redis的一个定义,来自官方的: Redis is an open source, BSD licensed, advanced key-value store. It is ofte ...
- hbase hmaster故障分析及解决方案:Timedout 300000ms waiting for namespace table to be assigned
最近生产环境hbase集群出现停掉集群之后hmaster无法启动现象,master日志报异常:Timedout 300000ms waiting for namespace table to be a ...
- ---Shell的数组遍历
1. 一一读入: read -a A < <(echo a b c d e f g) 2. 遍历输出
- 怎样增强MyEclipse的代码自动提示功能
步骤/方法 1 一 般在Eclipse ,MyEclipse代码里面,打个foreach,switch等 这些,是无法得到代码提示的(不信自己试试),其他的就更不用说了,而在Microsoft Vis ...
- 关于angularjS与jQuery框架的那些事
这篇文章主要介绍了jQuery和angularJS的区别浅析,本文着重讲解一个熟悉jQuery的程序员如何应对angularJS中的一些编程思想的转变吗,需要的朋友可以参考下 最近一直研究angula ...