OData 學習目錄html
上一篇已經完成了服務建立,本篇主要介紹如何經過Ajax請求Odata服務,OData操做主要有 Get、Post、Patch、Put、Delete等操做。ajax
Post 操做 json
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 操做 只修改有變化的實體屬性app
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 操做,修改全部實體async
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; } }); }