Passing parameters as string in ajax call

Passing parameters as string in ajax call

I have a javascript method which contains an ajax call:

  1. function MyFunction(urlTask, task) { ... ajax({ url: urlTask, data: task.Params, type: 'POST', dataType: 'json' }) ... }

urlTask is the name of a method in the controller (asp.net mvc 4), it varies depending on some conditions. As a example, it can be Task1, Task2,...:

  1.  [HttpPost] public ActionResult Task1(string Param1, string Param2) { } [HttpPost] public ActionResult Task2(string Param1) { }

Each controller method has a different number of parameters. So as controller method to be called from jquery ajax can vary as well as its parameters I use the commented scenario, passing the data to the javascript method and then passing it through the ajax call (url and data).

task.Params contains the parameters passed to the controller method (see below explanation).

What I want is to pass the 'Data' argument for ajax call using a parameter, in this case, an object called task that contains a string field named Params but it is not working, I mean, data received in the controller method for Param1 and Param2 for Task1 controller method are nulls.

task.Params contains a string like below when calling Task1 controller method:

  1. {'Param1':'Param_1','Param2':'Param_2'}

and:

  1. {'Param1':'Param_1'}

when calling Task2 controller method


Using below in the ajax call is not working::

  1. contentType: 'application/json',
  2. data: JSON.stringify(task.Params)


For some reason, the parameters passed through data to the method in the controller (asp.net mvc 4) are not interpreted correctly by the ajax call when sending them so in the controller side, the method is receiving the arguments (parameters) as nulls.

What's wrong?