Exploring how to operate ASP. NET Web API (3), asp. netapi
I believe you have no problem with webapi after my three articles are answered!
Create a UserModel first
public class UserModel{ public string UserID { get; set; } public string UserName { get; set; }}
Then add the Web API Controller
public class UserController : ApiController{ public UserModel getAdmin() { return new UserModel() { UserID = "000", UserName = "Admin" }; } }
Register a route
public static void Register(HttpConfiguration config){ config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );}
Register in Global
protected void Application_Start(object sender, EventArgs e){ WebApiConfig.Register(GlobalConfiguration.Configuration);}
In this case, use the address bar to access the address: api/user/getadmin.
The XML data model is returned by default.
Use AJAX to request this api and specify the data format as json
$.ajax({ type: 'GET', url: 'api/user/getadmin', dataType: 'json', success: function (data, textStatus) { alert(data.UserID + " | " + data.UserName); }, error: function (xmlHttpRequest, textStatus, errorThrown) { }});
The result of alert is:
In this case, dudu says that the specified data format can be returned Based on the Data Type of the request.
POST Data
Modify the controller and add an add method.
public bool add(UserModel user){ return user != null;}
Only for testing, so here only judge whether the input object is null. If not empty, true is returned.
I added a button on the page. The Code is as follows:
<Input type = "button" name = "btnOK" id = "btnOK" value = "Send POST request"/>
Add JS Code
$ ('# Btnok '). bind ('click', function () {// create an ajax request and send the data to the backend for processing var postData = {UserID: '001', UserName: 'qeeket'}; $. ajax ({type: 'post', url: 'api/user/add', data: postData, ype: 'json', success: function (data, textStatus) {alert (data) ;}, error: function (xmlHttpRequest, textStatus, errorThrown ){}});});
Run the page again
We append the process for debugging. When sending an ajax request, the data received by the server segment
If you think this article is helpful, don't forget to support it!
Author: Qi Fei Source: http://youring2.cnblogs.com/