OData V4 Ajax request CRUD, odatacrud
OData learning directory
The previous article has completed service creation. This article mainly describes how to request Odata services through Ajax. OData operations include Get, Post, Patch, Put, Delete, and other operations.
Post Operation
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"}; // Create Product Information $. 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 ;}});}
The Patch operation only modifies the changed object attributes.
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}; // Create Product Information $. 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 operation to modify all objects
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 operation
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; } }); }