How to pass formcollection using ajax call to an action?
If anyone want to pass additional data to the FormCollection then you can try below.
<script type="text/javascript">
function SubmitInfo()
{
var id = $("#txtid").val();
var formData = $('#yourformname').serializeObject();
$.extend(formData, { 'User': id }); //Send Additional data
$.ajax({
url: 'Controlle/GetUser',
cache: false,
type: 'POST',
dataType: 'json',
data: decodeURIComponent($.param(formData)),
success: function (data) {
$('#resultarea').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
<script/>
Action Method
public ActionResult GetUser(FormCollection frm)
{
int UserId = Convert.ToInt32(frm["user"]);
// your code
return Json(data, JsonRequestBehavior.AllowGet);
}
Refer link for more details.
Try:
$(<your form>).on('submit',function(){
$.ajax({
url: "/Register/CompleteRegisteration" + $(this).serialize(),
// place the serialized inputs in the ajax call
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.result == "Error") {
alert(data.message);
}
}
});
});
Since FormCollection
is a number of key-value pairs, JSON is inappropriate data format for its representation. You should use just serialized form string:
var form = $("#onlineform").serialize();
$.ajax({
type: 'POST',
url: "/Register/CompleteRegisteration",
data: form,
dataType: 'json',
success: function (data) {
if (data.result == "Error") {
alert(data.message);
}
}
});
Key changes:
- type of the request set to POST (not necessary here, but seems more natural)
- Serialized form instead of JSON string as request data
- contentType removed - we are not sending JSON anymore