上一篇已经完成了服务创建,本篇主要介绍如何通过Ajax请求Odata服务,OData操作主要有 Get、Post、Patch、Put、Delete等操作。
Post 操作
public async Task<IHttpActionResult> Post(Product product) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _dbContext.Products.Add(product); await _dbContext.SaveChangesAsync(); return Created(product); }
function addPro() { var pro = { Name: "OData Create", Price: 1024, Category: "IT" }; //创建产品信息 $.ajax({ url: "/Odata/Products", type: "POST", contentType: "application/json; charset=utf-8", dataType: "JSON", data: JSON.stringify(pro), success: function (r) { alert(r.Id); }, error: function (e) { debugger; } }); }
Patch 操作 只修改有变化的实体属性
public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Product> product) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var entity = await _dbContext.Products.FindAsync(key); if (entity == null) { return NotFound(); } product.Patch(entity); try { await _dbContext.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { throw; } return Updated(entity); }
var pro = { SupplierId: 2 }; //创建产品信息 $.ajax({ url: "/Odata/Products(" + id + ")", type: "Patch", contentType: "application/json; charset=utf-8", dataType: "JSON", data: JSON.stringify(pro), success: function (r) { debugger; }, error: function (e) { debugger; } });
Update 操作,修改所有实体
public async Task<IHttpActionResult> Put([FromODataUri] int key, Product update) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (key != update.Id) { return BadRequest(); } _dbContext.Entry(update).State = EntityState.Modified; try { await _dbContext.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!Exists(key)) { return NotFound(); } else { throw; } } return Updated(update); }
Delete 操作
public async Task<IHttpActionResult> Delete([FromODataUri] int key) { var product = await _dbContext.Products.FindAsync(key); if (product == null) { return NotFound(); } _dbContext.Products.Remove(product); await _dbContext.SaveChangesAsync(); return StatusCode(HttpStatusCode.NoContent); }
function deletePro(id) { $.ajax({ url: "/Odata/Products(" + id + ")", contentType: "application/json; charset=utf-8", type: "Delete", success: function (r) { debugger; }, error: function (r) { debugger; } }); }