简体   繁体   中英

Ajax not posting data to controller

I am posting data through ajax to a action, but the problem I am not able to get the data posted through ajax in my controller action. While debugging, the call gets transferred to action but I dont get anything in data not even 'null'.

here is my ajax call,

 $.ajax({
            type: 'POST',
            url:' @Url.Action("PostAmount", "Deal")',
            data: { country: 2, amount: 4.02 },
            datatype:JSON,

            success: function (data) {
                alert("hiiii"+data);
            }
        });

and my action,

 [HttpPost]
        public JsonResult PostAmount(int country,double amount)
        {
            AllocationViewModel mod = new AllocationViewModel();
            return Json(mod);
        }

Try this:

var dataToPost = "{ country:'" + 2 + "', amount:" + 4.02 + "}";

$.ajax({
    url: @Url.Action("PostAmount", "Deal")',
    type: "POST",
    dataType: 'json',
    data: dataToPost,
    cache: false,
    contentType: "application/jsonrequest; charset=utf-8",
    success: function (data) {
        alert("hi"+ data);
    }
});

try the following:

$.ajax({
        type: 'POST',
        url:' @Url.Action("PostAmount", "Deal")',
        data: { "country": "2", "amount": "4.02" },
        datatype:JSON,

        success: function (data) {
            alert("hiiii"+data);
        }
    });

or the best solution is to save the values in an object and use the jquery function "stringify" and then send the values over. that should work.

try putting json in quotes

$.ajax({
    type: 'POST',
    url:'@Url.Action("PostAmount", "Deal")',
    data: { country: "2", amount: "4.02" },
    dataType:"json",
    traditional:true,
    success: function (data) {
        alert("hiiii"+data);
    }
});

You could also use JSON.stringify(yourObject) on your object to make it a JSON object. This makes it easier to create objects in javascript and pass then into the data parameter of your post request. Also use a string for the datatype parameter ( https://api.jquery.com/jquery.post/ ), as suggested in the answers above.

var dataToPost = { country: 2, amount: 4.02 };

$.ajax({
    type: 'POST',
    url:' @Url.Action("PostAmount", "Deal")',
    data: JSON.stringify(dataToPost),
    datatype: 'json',
    success: function (data) {
        alert("hiiii"+data);
    }
});

The other way around is JSON.parse(yourJsonObject) . This way you can parse a JSON string into a Javascript object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM