Asp.net MVC Controller Action string parameter not passed

In my controller I have

public JsonResult GetInfo(string id) 

in my js

  $.ajax({ contentType: 'application/json, charset=utf-8', type: "POST", url: "/Incidents/GetInfo", data: { id: "777" }, cache: false, dataType: "json", success: function (response) { //etc.... 

jquery ajax error is delegated. If i use

  data: { "777" }, 

no error, but the value is not transmitted. It should be easy, but I hit my head against the wall. Maybe I'm not allowed to pass strings to controller actions?

What am I doing wrong here?

+4
source share
2 answers

You specify the application/json request and you send the application/x-www-form-urlencoded request. Thus, you will need to choose one of two ways to encode parameters, rather than mixing them.

application/x-www-form-urlencoded :

 $.ajax({ type: "POST", url: "/Incidents/GetInfo", data: { id: "777" }, cache: false, dataType: "json", ... }); 

application/json :

 $.ajax({ type: "POST", url: "/Incidents/GetInfo", contentType: 'application/json, charset=utf-8', data: JSON.stringify({ id: "777" }), cache: false, dataType: "json", ... }); 

The JSON.stringify method JSON.stringify built into modern browsers and is used to convert a javascript literal to a JSON string, which we indicated that we would send the request as. If you need to support legacy browsers, you can include the json2.js script in your page that contains this method.

As a side note, the dataType: "json" parameter is not needed, as the server will set the correct Content-Type header to application/json , and jQuery is smart enough to use it.

And as a second note, you really do not want your javascript file to have a hard-coded URL: url: "/Incidents/GetInfo" . You want to use URLs when creating URLs: url: "@Url.Action("GetInfo", "Incidents")" .

+12
source

Are you missing the HttpPost attribute in your action? If not, use something like firebug or chrome dev to see the http request / response and get more details ...

 [HttpPost] public JsonResult GetInfo(string id) 
0
source

Source: https://habr.com/ru/post/1381411/


All Articles