Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC Controller Action string parameter doesn't get 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 delegate gets executed. If I use

 data: { "777" },

no error, but the value doesn't get passed. This should be easy but I am beating my head against the wall. Maybe I am not allowed to pass strings to controller's actions?

What am I doing wrong here?

like image 685
sarsnake Avatar asked Dec 16 '22 07:12

sarsnake


1 Answers

You are indicating application/json request and you are sending a application/x-www-form-urlencoded request. So you will have to choose between one of the two ways to encode parameters and not mix 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 is natively built into modern browsers and is used to convert the javascript literal into a JSON string which is what we indicated that we are going to send the request as. If you are having to support legacy browsers you could include the json2.js script to your page which contains this method.

As a side note the dataType: "json" setting is not needed since the server will set the proper Content-Type header to application/json and jQuery is smart enough to use that.

And as a second side note you really don't want to be hardcoding an url like this in your javascript file: url: "/Incidents/GetInfo". What you want is to use url helpers when generating urls: url: "@Url.Action("GetInfo", "Incidents")".

like image 158
Darin Dimitrov Avatar answered May 19 '23 20:05

Darin Dimitrov