C # Post request for passing parameters through WebApi-AJAX,

Source: Internet
Author: User
Tags tojson

C # Post request for passing parameters through WebApi-AJAX,

I recently learned a truth, and I will share it with you here: Education represents your past, your present abilities represent your present, and learning represents your future.

Ten years in Hexi, do not bully teenagers poor.

There is no end to learning, keep improving

The previous section describes the Get request for passing parameters in C # WebApi-AJAX.

This section describes C # Post request for passing parameters through WebApi-AJAX. When talking about Ajax Post requests for webApi, it is really not flattering. It is really weird, if you unfortunately want to write an Ajax Post request to the webApi interface, you still need to spend some time reading this blog. If you have encountered the same problem, you may wish to give this blog a thumbs up at the end. Thank you.

Speaking of Post requests, we must be familiar with it. The principle of post requests is different from that of get requests. We know that the parameters of get requests are transmitted through URLs, THE post request is transmitted through the http Request body. The WebApi post request also needs to retrieve parameters from the http Request body. To put it bluntly, a Get request transmits a set of key-value pairs through a URL, and a Post request sends an Http request body. In the previous Get request, we used the [FromUri] keyword. For Post requests in this section, we will use another keyword [FromBoay]. At the end of the previous section, we recommend that you include the [FromUri] keyword in Get requests. Likewise, for Post requests in this section, I suggest you include the [FromBody] keyword when receiving parameters. After all, it is not a bad thing to develop a good habit.

As mentioned in the beginning, the Ajax Post request webApi is weird. How is it weird? The following code demonstrates that: <this article still uses the object of the Get request in the previous section. For details about unknown bloggers, refer to my previous blog>

As follows:

/// <Summary> /// simple test case /// </summary> /// <returns> </returns> [HttpPost] public string Get () {return "OK ";} /// <summary> /// obtain specific data by id /// </summary> /// <param name = "Id"> </param> // <returns> </returns> [HttpPost] public string GetById ([FromBody] int Id) {list = list. where (p => p. id = Id ). toList (); return JsonHelper. jsonSerializer <List <Person> (list );}

AJax is as follows:

// Request without parameters-simple example $ (document). ready (function () {$. ajax ({url :" http://localhost:9953/api/Person/Get ", Type:" post ", contentType:" application/json ", dataType:" text ", data :{}, success: function (result, status) {if (status = "success") {alert (result) ;}}, error: function (error) {alert (error );}});}); // pass-data: {"": "3"} for a single parameter. This method is also correct $ (document ). ready (function (data) {$. ajax ({url :" http://localhost:9953/api/Person/Get ById ", type:" post ", contentType:" application/json ", dataType:" text ", data: {Id:" 3 "}, success: function (result, status) {alert (result)}, error: function (error) {alert (error );}});});

In the above JS, the comment has the following sentence: 'Data: {"": "3"}. This method is also correct'

This is another way of writing that many people have a headache, but there is no way. After testing, this method is indeed correct.

Based on the above case, we can see the method for passing a single parameter in the Post request. Can we use the following method if multiple parameters are passed? (According to the test, the following statement is incorrect, and 404Not Found is reported)

  $(document).ready(function (data) {            $.ajax({                url: "http://localhost:9953/api/Person/GetByIdAndSex",                type: "post",                contentType: "application/json",                dataType: "text",                data: { Id: "3",Sex:"W" },                success: function (result, status) {                    alert(result)                },                error: function (error) {                    alert(error);                }            });        });
/// <Summary> // incorrect syntax. Of course, this article only describes Ajax requests. If you make requests through HttpwebClient, this method has no problem. // </summary> /// <param name = "Json"> </param> /// <returns> </returns> [httpPost] public HttpResponseMessage GetByIdAndSex ([FromBody] string Id, [FromBody] string Sex) {List <Person> list_2 = new List <Person> (); var Result = from r in list where r. id = Convert. toInt32 (Id) & r. sex = Sex select r; foreach (var Item in Result) {list_2.Add (Item);} return ResultToJson. toJson (list_2 );}

The test result is: the Id and Sex value cannot be obtained! At the beginning, we will say that the Get request method is to pass the key-value pair through the URL, while the Post request is to pass an Http request body, while the JS data: {Id: "3 ", sex: "W"} uses the key-Value Pair type, while the Post request cannot read the key-Value Pair drops. Therefore, the preceding statement is incorrect.

So, you may ask, why is there no problem with a parameter request? Why is there no problem with the two parameters? This... the answer I can give is: this is the strange thing about Post Ajax requests.

What should I do if I write it correctly?

We know that the Get request is a part-time pair, and the Post request is the Http Request body. According to my understanding, the Post request needs to send a parameter as the Http Request body, this parameter is a whole, not a set of key-value pairs. Therefore, we make the following changes:

The Code is as follows:

// Multiple parameters are passed $ (document ). ready (function (data) {$. ajax ({url: "http: // localhost: 9953/api/Person/GetByIdAndSex", type: "post", contentType: "application/json", dataType: "text", data:JSON. stringify ({Id:"3", Sex: "W"}), Success: function (result, status) {alert (result)}, error: function (error) {alert (error );}});});
/// <Summary> // The incorrect syntax is 2. It is strange. // </summary> /// <param name = "Json"> </param> /// <returns> </returns> [HttpPost] public HttpResponseMessage GetByIdAndSex ([FromBody] string Json) {string Id = JsonHelper. getJsonValue (Json, "Id"); // obtain Id string Sex = JsonHelper. getJsonValue (Json, "Sex"); // obtain the sex List <Person> list_2 = new List <Person> (); var Result = from r in list where r. id = Convert. toInt32 (Id) & r. sex = Sex select r; foreach (var Item in Result) {list_2.Add (Item);} return ResultToJson. toJson (list_2 );}

The above annotation is a red and bold JS code. We will convert the Post key-value pair into a Json string and pass it to the backend. In the backend code, we try to receive the JSon string and parse it to read the Id and Sex values. According to the Post request rules, we only send one Http Request body, and received at the backend. Should there be no problem this time?

The actual test result is: The 404 Not Found error will Not occur, but the Post string cannot be received, that is, the Json in [FromBody] string Json is Null, (⊙ o ⊙ )...

No. How can this problem be solved?

When I get off work, I don't need to spray it any more. I 'd like to tell you some notes:

When receiving data from the backend, the parameter type should be dynamic. In JS Code, the corresponding contentType must be added. The Post value must be a whole, not a key-value pair. In JS, the Type must be Post, and the backend receiving Type must be [HttpPost]. If no value is added, the default Type is [HttpGet.

The following is a sample code to help you:

1. Multiple parameters are passed:

// Multiple parameters are passed $ (document ). ready (function (data) {$. ajax ({url: "http: // localhost: 9953/api/Person/GetByIdAndSex", type: "post", contentType: "application/json", dataType: "text", data: JSON. stringify ({Id: "3", Sex: "W"}), success: function (result, status) {alert (result)}, error: function (error) {alert (error );}});});
 [HttpPost]        public HttpResponseMessage GetByIdAndSex([FromBody]dynamic Json)        {            string Id = Json.Id;            string Sex = Json.Sex;            List<Person> list_2 = new List<Person>();            var Result = from r in list                         where r.Id == Convert.ToInt32(Id) && r.Sex == Sex                         select r;            foreach (var Item in Result)            {                list_2.Add(Item);            }            return ResultToJson.toJson(list_2);        }

2. transfer an object data

// Pass the object array $ (document ). ready (function (data) {var dataList = [{Id: "8888", Sex: "male", Name: "Chen Wolong", Age: "26 "}, {Id: "8887", Sex: "male", Name: "Chen Dalong", Age: "27" },{ Id: "8886", Sex: "male ", name: "Chen Xiaolong", Age: "25"}]; $. ajax ({url: "http: // localhost: 9953/api/Person/GetByObjectList", type: "post", contentType: "application/json", dataType: "text", data: JSON. stringify (dataList), success: function (result, status) {alert (result)}, error: function (error) {alert (error );}});});
/// <Summary> /// the object array is used as the parameter /// </summary> /// <param name = "P"> </param> /// <returns> </returns> [HttpPost] public HttpResponseMessage GetByObjectList ([FromBody] dynamic Plist) {List <Person> list = new List <Person> (); foreach (var item in Plist) {Person person = new Person () {Name = item. name, Sex = item. sex, Id = item. id, Age = item. age,}; list. add (person);} return ResultToJson. toJson (list );}

So far: pOst requests are all done.

We know that there are four major requests: Get, Post, Put, and Delete. Put and delete requests use the Post request principle. They are similar in that they are simply Put requests for modification and insertion, delete request for deletion. Therefore, Put Delete requests can all adopt the request method described in this article, but they do different actions!

Okay, go home and enjoy the steamed fish. You have recently learned some delicious food. You are welcome to try it. We will mail it to you! Haha

@ Chen Wolong's blog

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.