C# web Api ajax发送json对象到action中
直接上代码:
1.Product实体
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AjaxAPIWeb.Models { public class Product { public int Id { get; set; } public string Name { get; set; } } }
2.index.html页面
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="Scripts/jquery-1.8.2.js"></script> </head> <body> <input type="button" value="提 交" id="add" /> <script type="text/javascript"> $(function () { $("#add").click(function () { $.ajax({ url: "/api/Product/GetProduct", data: JSON.stringify({ Id: 1, Name: "张三" }), dataType: "json", type: "POST", contentType: "application/json", success: function (data) { console.log(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + ": " + errorThrown); } }) }) }); </script> </body> </html>
3.ProductController
using AjaxAPIWeb.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace AjaxAPIWeb.Controllers { public class ProductController : ApiController { [HttpPost] public object GetProduct(Product productModel) { string result = ""; int id = productModel.Id; string name = productModel.Name; result = "id:" + id + "name:" + name; return result; } } }
最终的效果如下:
(本人微信号:Liberty-bcy)如果,你正在埋怨命运不眷顾,那请记住:命,是失败者的借口;运,是成功者的谦词。