0

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 ?

4
  • Try adding this property to your ajax call: contentType: 'application/json' and wrapping the data in JSON.stringify({ processName: "MyProc", startDate: "2015-08-01 16:00"}) Commented Aug 4, 2015 at 15:51
  • i copy all the code to my vs and seem working perfectly Commented Aug 4, 2015 at 15:58
  • @RoryMcCrossan that attribute is from WebAPI dll.. I cannot use it Commented Aug 4, 2015 at 16:01
  • Using JSON in MVC2 isn't straight-forward: stackoverflow.com/questions/6479534/asp-net-ajax-with-mvc2 Commented Aug 5, 2015 at 4:23

3 Answers 3

1

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

     }
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Changed it to: $.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) { } });
and I'm reaching "int i=1;" row, but STILL getting nulls in those two vars :(
0
    $.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) {
    }
    });

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.