If you need to send more than one value to a controller action from an ajax call, you can wrap those values together into a business object and send that to the controller action. Jquery automagically maps your javascript object to your controller action’s business object. If you’ve sent a fill-grid object from a jqgrid call, you may notice that the syntax is very similar. Here’s how:
In your ajax call be sure your type is Get, your url is set to your dynamically generated MVC controller action, and in your “data” property call a BuildGridObject javascript function, like this:
function LoadSender() {
$.ajax({
url: '',
success: function(data) {
// fill the ddl with the data from the json call
var ddl = $('#ddlTransferTo');
optionArray = [];
$.each(data, function(i, option) {
optionArray[i] = "<option value="" + option.Value + "">" + option.Disp + "</option>";
});
ddl.children().remove();
ddl.append(optionArray.join(''));
},
data: BuildGridObject (),
type: "GET",
dataType: 'json'
});
}
In your BuildGridObject function, create a new object and assign the values to the properties you want to send to the controller action. In this example, selected values are pulled from a drop down list. Note: your javascript object won’t have intellisense for the properties of your business object, so you’ll have to copy/paste them manually into the javascript object. Like this:
function BuildGridObject (){
var objToSend = new Object();
objToSend.TransferFrom = $('#ddlTransferFrom').val();
objToSend.TransferTo = $('#ddlRegion').val();
return objToSend;
}
Create your business object in the usual place, like this:
namespace Models
{
public class Transfer
{
public long TransferTo{ get; set; }
public long TransferFrom { get; set; }
}
}
Finally, make sure your controller action accepts the business object in its parameter, like this:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetList(Transfer transfer)
{
try
{
returnJson(myBLL.GetScreenerList(transfer.TransferTo, transferTo.TransferFrom));
}
catch (Exception ex)
{
return HandleError(ex, null);
}
}