1

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);
        }
1
  • see in console that on your given url request is going or not Commented Mar 10, 2014 at 5:33

4 Answers 4

5

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);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

still not getting the data in controller :(
0

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);
    }
});

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.