ohadinho
ohadinho

Reputation: 7144

"POST" data with jquery ajax and MVC2

I'm using MVC2, and I'm trying to send data with jquery ajax.

There is my JS code:

$.ajax({
    type: "POST",
    url: "Data",
    data: { processName: "MyProc", startDate: "2015-08-01 16:00"},
    success: function(data) {
    }
});

And there is my controller:

[HttpPost]
public JsonResult Data(string processName, string startDate)
{
    int i = 1;
}

So my problem is that I DO get to "int i=1;" line in my controller, BUT for some unknown reason - processName and startDate are both null.

Can someone please assist ?

Upvotes: 0

Views: 84

Answers (3)

Ansary Ans21
Ansary Ans21

Reputation: 462

    $.ajax({
                url: '@Url.Action("ActionName", "ControllerName")',
                type: 'POST',
                data:  JSON.stringify({ processName: "MyProc", startDate: "2015-08-01 16:00"}),
                contentType: 'application/json; charset=utf-8',
                success: function (responseData) {
    }
    });

Upvotes: 0

Ju66ernaut
Ju66ernaut

Reputation: 2691

Try making a model and using that for the parameter in your action

  public class MyModel
{
    public string processName { get; set; }

    public string startDate { get; set; }
}

then

[HttpPost]
    public JsonResult Data(MyModel model)
    {
       int i = 1;
        //model.processName
        //model.startDate

     }

Upvotes: 1

Pavel Morshenyuk
Pavel Morshenyuk

Reputation: 11471

Try to add content type and data type in your jquery code + stringify your data:

$.ajax({
  type: "POST",
  url: "Data",
  data: JSON.stringify({ processName: "MyProc", startDate: "2015-08-01 16:00"}),
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  success: function(data) {
  }
});

Upvotes: 0

Related Questions