ASP. net mvc WebAPI operations (ADD, update, and delete), mvcwebapi
Yesterday's "how to operate WebAPI interface (display data)" http://www.cnblogs.com/insus/p/5670401.html
You can use jQuery or HttpClient to obtain data from the database and display the data in the ASP. net mvc view.
Today, Insus. NET wants to complete all the examples, that is, to add, update, and DELETE other functions to POST, PUT, and DELETE Web APIs.
Create three operations from the Controller, that is, the so-called actions. They are POST (ADD), PUT (update), and DELETE (DELETE ):
Throughout the Web API access process, if the API method is named with the default method name, all connection addresses are the same.
PostDataToApi. cshtml View:
$ (Function () {$ ("# Button1 "). on ("click", function () {var obj = {}; obj. sizeName = $ ("# Text1 "). val (); $. ajax ({type: "POST", url: "http: // localhost: 9001/api/size", dataType: "json", contentType: "application/json; charsets = UTF-8 ", data: JSON. stringify (obj), success: function (data) {alert ("data added successfully! ") ;}, Error: function (jqXHR, textStatus, errorThrown) {alert (errorThrown );}});});});Source Code
PutDataApi. cshtml View:
Jquery Code marked with #4:
$ (Function () {$ ('table '). on ('click', '# Button1', function () {var row = $ (this ). closest ('tr'), cells = row. find ('td '); var obj ={}; obj. size_nbr = cells. find ("input: hidden [id = Hidden1]"). val () obj. sizeName = cells. find ("input [id = 'text1']"). val (); $. ajax ({type: "PUT", url: "http: // localhost: 9001/api/size", data: JSON. stringify (obj), dataType: "json", contentType: "application/json; charset = UTF-8 ", Success: function (data) {alert (" Update successfully! ") $ (Location ). attr ('href ', "PutDataApi") ;}, error: function (jqXHR, textStatus, errorThrown) {alert (errorThrown );}});});});Source Code
DeleteDataApi. cshtml View:
Code of the jQuery deletion function marked with #3:
$ (Function () {$ ('table '). on ('click', '# Button1', function () {var row = $ (this ). closest ('tr'), cells = row. find ('td '); var obj ={}; obj. size_nbr = cells. find ("input: hidden [id = Hidden1]"). val () $. ajax ({type: "Delete", url: "http: // localhost: 9001/api/size", data: JSON. stringify (obj), dataType: "json", contentType: "application/json; charset = UTF-8", success: function (data) {alert ("Delete success Fully! ") Row. remove () ;}, error: function (jqXHR, textStatus, errorThrown) {alert (errorThrown );}});});});Source Code
OK. All the above three functions have been shared. Let's take a look at the actual running functions:
Add data to Web APIs:
Modify Web API data:
Demo of deleting Web API data: