Reputation: 2464
I want to pass multiple parameter with ajax call.
Ajax function:--
$.ajax({
url: 'Home/SaveData',
type: 'POST',
data: {"data" : data + "id" : 1}, //<-- I want to send data and id
dataType: "application/JSON",
success: function (result) {
alert("Success");
},
error: function (result) {
data.str = null;
alert("Error");
},
});
}
-----Controller
[HttpPost]
public JsonResult SaveData(string data,int id)
{
foreach (string s in data.Split(','))
{
if (!string.IsNullOrEmpty(s))
{
//Perform your opeartion here
}
}
return Json("");
}
Regards, vinit
Upvotes: 0
Views: 1248
Reputation: 1889
When setting up your data as a JSON object you need to use a comma instead of a plus to make it a valid object of key value pairs:
$.ajax({ url: 'Home/SaveData',
type: 'POST',
data: {"data" : data, "id" : 1},
dataType: "application/JSON", success: function (result) { alert("Success");
},
error: function (result) {
data.str = null;
alert("Error");
},
});
}
This should now bind to your two action parameters.
Upvotes: 2
Reputation: 1154
When using $.ajax you can see that it uses javascript objects to handle everything. The data property you set wants another javascript object.
data:{data:data, id:id}
$.ajax({
type: "POST",
url: "http://example.url.tosendto",
data: { data: data, id: id} // Data property of the object wants another javascript object
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
Upvotes: 1