3

I'm facing a problem when calling an action on a controller with an argument

In the controller i have following action:

[HttpPost]
public ActionResult UpdateData(string month)
{
    return Json(new { success = true, message = "Hello world" });
}

The ajax call in the view looks like:

$.ajax({
    url: '@Url.Action("UpdateData")',
    dataType: "json",
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    cache: false,
    data: {  },
    success: function (data) {
        if (data.success) {
            alert(data.message);
        }
    },
    error: function (xhr) {
        alert(xhr.responseText);
    }
});

this works well, but when i want to pass the argument like

data: {month:'may'} 

i get an error, the action is never called. I just don't see it.


EDIT :

Ok, i just had to pass the json as a string:

data: "{month:'may'}"

I think i need more sleep :-)

3
  • Please note that the model-view-controller tag is for questions about the pattern. There is a specific tag for the ASP.NET-MVC implementation. Commented Sep 18, 2016 at 10:21
  • 1
    What you need to do is remove contentType: 'application/json; charset=utf-8', and use data: {month:'may'} Commented Sep 18, 2016 at 10:22
  • It works, thanks! And i'll use the asp.net-mvc tag next time ;-) Commented Sep 18, 2016 at 10:27

1 Answer 1

3

You have to just remove content type and also better if you pass controller name in URL:

 $.ajax({
        url: '@Url.Action("UpdateData","YourControllerName")',
        dataType: "json",
        type: "POST",            
        cache: false,
        data: {month:'may'} ,
        success: function (data) {
            if (data.success) {
                alert(data.message);
            }
        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
});
Sign up to request clarification or add additional context in comments.

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.