How do I POST collection of data to controller action - ajax

I have following code to send DATA to controller action and return the plain HTML
I am getting empty object in controller action.
var employees = [
{ Title: "John", DataType: 1 },
{ Title: "Anna", DataType: 2 },
{ Title: "Peter", DataType: 3 }
];
$("#btn-continueedit").click(function () {
$.ajax({
type: 'POST', // I tried post also here
cache: false,
url:'/user/UserinfoWizard',
data: { values: employees },
success: function (data) {
$("#editUserInfo").html(data);
}
});
return false;
});
Here is my controller action
[HttpPost]
public ActionResult UserInfoWizard(List<UserInfoEditDetail> values)
{
// I get empty object 'values' here :(
}

The data passed with the ajax call should be an object containing the parameter which you want to use in the controller action. Your action expects a values parameter passed with the data, so your data object should be data: { values: getSelectedAttributes() }
JavaScript:
$("#btn-continueedit").click(function () {
$.ajax({
type: 'POST',
//..
data: { values: getSelectedAttributes() }, //Use the data object with values
//..
});
return false;
});
C#:
[HttpPost]
public ActionResult UserInfoWizard(object values) // parameter name should match the name passed in data object
{
//..
}
EDIT
Indeed you action expects an object, while your values is an array. I don't know what the values are, but in your action you should have the int[] values or string[] values as parameter or any other array type you are expecting.

$("#btn-continueedit").click(function () {
$.ajax({
type: 'GET', // I tried post also here
cache: false,
dataType:JSON,
url:'/user/UserinfoWizard',
data: JSON.stringify({ data:getSelectedAttributes()}),
success: function (data) {
$("#editUserInfo").html(data);
}
});
return false;
});
Updated:
When you are passing data during an ajax call, it should be in the form of an object and not an array

Related

Passing multiple ajax parameters to mvc controller

I can pass a serialized form to a mvc controller no problems with code below and all is populated
$("#btnExecuteJob").on("click", function (e) {
var frmForm1 = $("#form1").serialize();
$.ajax({
cache: false,
url: "/mvcController/executeJob",
dataType: 'json',
type: 'POST',
data: frmForm1,
success: function (resp) {},
error: function (resp) {}
});
});
Controller
[HttpPost]
public ActionResult executeJob(runDetails jobDetails)
{
//
// Process
//
return View();
}
I have added a second form to my view and now want to pass both to the controller so I tried
$("#btnExecuteJob").on("click", function (e) {
var frmForm1 = $("#form1").serialize();
var frmForm2 = $("#form2").serialize();
$.ajax({
cache: false,
url: "/jobScheduler/executeJob",
dataType: 'json',
type: 'POST',
data: {
jobDetails: frmForm1,
jobParameters: frmForm2
},
success: function (resp) {},
error: function (resp) {}
});
});
Controller
public ActionResult executeJob(runDetails jobDetails, runParams jobParameters)
{
//
// Process
//
return View();
}
and neither jobDetails or jobParams is populated, both work individually as first example
and all details are populated, any help much appreciated,
both forms really need to be separate in the controller

Data from ajax post is passing null to the controller

AJAX call -
Here countryId is passed as "AU" for example -
$("#Countries").change(function () {
var countryId = this.value;
$.ajax({
url: '/Registers/GetStates',
type: "POST",
data: { 'data': countryId },
success: function (states) {
$("#States").html(""); // clear before appending new list
$.each(states, function (i, state) {
$("#States").append(
$('<option></option>').val(state.Id).html(state.Name));
});
}
});
});
After calling the GetStates method 'countryId' is always passed as null in the controller method. Not sure what I'm missing here.
I tried JSON.Stringify({ 'data': countryId }) also. Can anyone help me out ?
Controller Action -
[HttpPost]
public SelectList GetStates(string countryId)
{
return Helper.GetStates(countryId);
}
The parameter in your action method should be exactly same as the parameter name in the 'data' option of ajax.
In your case it is 'countryId'
[HttpPost]
public SelectList GetStates(string countryId)
{
return Helper.GetStates(countryId);
}
Change your ajax data option accordingly.
data: { countryId: countryId },
It will work.

Passing multiple objects to my controller

I am passing an object to my controller like so:
var form = JSON.stringify({
"subRevisedRequest": $('#frmRevised').val(),
"subSubcontractor": $('#frmSubcontractor').val(),
"subDescription": $('#frmDesc').val(),
"subCostCode": $('#frmCostCode').val(),
"subAmt": $('#frmAmt').val(),
"subPaymentTerms": "terms",
"subRetainage": 10,
"subComments": $('#frmComment').val()
});
$.ajax({
url: '#Url.Action("CreateSubcontracts", "Routing")',
type: "POST",
datatype: "JSON",
contentType: "application/json; charset=utf-8",
data: form,
success: function(result) {
if (!result.success) {
$('#errormsg').empty();
$('#errormsg').append(result.message);
} else {
location.href = '#Url.Action("Index", "Home")';
}
},
error: function (result) {
alert("Failed");
}
});
my controller sees this as the object it is looking for:
public ActionResult CreateSubcontracts(RoutingSubcontracts s)
My problem is that I'd like to pass along just one more string. I know I can make a view specific model but I was wondering if I could do something like this for example:
public ActionResult CreateSubcontracts(RoutingSubcontracts s, string bu)
I have tried the the following with no luck:
data: JSON.stringify({ "s": form, "bu": "251" }),
but the complex object just comes through as null. Is there a way I can pass the object and a string through as well?
Try adding the string item in the JSON you already have. Dont stringify it or it will just send a big string that youll have to parse again on the server.
var form = {
"subRevisedRequest": $('#frmRevised').val(),
"subSubcontractor": $('#frmSubcontractor').val(),
"subDescription": $('#frmDesc').val(),
"subCostCode": $('#frmCostCode').val(),
"subAmt": $('#frmAmt').val(),
"subPaymentTerms": "terms",
"subRetainage": 10,
"subComments": $('#frmComment').val(),
"bu": "251" // add it here
};
$.ajax({
url: '#Url.Action("CreateSubcontracts", "Routing")',
type: "POST",
datatype: "JSON",
data: form,
success: function(result) {
if (!result.success) {
$('#errormsg').empty();
$('#errormsg').append(result.message);
} else {
location.href = '#Url.Action("Index", "Home")';
}
},
error: function (result) {
alert("Failed");
}
});
In your view jquery create a second var for bu. Assign the data in you ajax call like this;
data: { "s" : form, "bu" : "251" }
In your controller method change the signature to include a default value for bu like this;
public ActionResult CreateSubcontracts(RoutingSubcontracts s, string bu = "NoValue")
With the default value set bu will act like an optional parameter

Knockout object passed to Controller as JSon MVC ASP.Net

I am trying to pass knockout object as below,
When i pass the data using // ko.utils.postJson only without any the AJAx the data is passed to my controller to the "task", but when i try to post by Ajax I get a null value for task
function TaskListViewModel() {
var self = this;
self.availableMeals = [
{ UserName: "Standard", UserId: 0 },
{ UserName: "Premium", UserId: 34 },
{ UserName: "Ultimate", UserId: 290 }
];
self.save = function () {
// ko.utils.postJson(location.href, { task: this.availableMeals });
$.ajax(location.href,{
data: ko.toJSON({ task: this.availableMeals });,
type: 'POST',
dataType:'json',
contentType: 'application/json',
success: function (result) { alert(result) }
});
};
}
ko.applyBindings(new TaskListViewModel());
To the Controller as below,
[HttpPost]
public ActionResult About([FromJson] IEnumerable<UserProfile> task)
{
return RedirectToAction("Login","Account");
}
I would try changing your code to call the stored self reference in your Ajax call as follows:
$.ajax(location.href,{
data: ko.toJSON({ task: self.availableMeals });,
type: 'POST',
dataType:'json',
contentType: 'application/json',
success: function (result) { alert(result) }
});
};
I'm guessing that you are having a scope issues where this is losing it's reference in your Ajax call.

How to dynamically pass data parameter in a jquery ajax call (multiple arrays of data)

I have this ajax code:
return $.ajax({
type: "POST",
url: "somefile.php",
cache:false,
data: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
dataType:"json",
success: function(data){
alert("success");
}
This works fine, but I need to pass the data parameter dynamically. For now I need the above data parameter content and a single string.
How do I pass this dynamically? / How do I store it in a variable and pass it to the "data:" field?
{ "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() }
I tried JSON.stringify I I couldn't get it to work probably due to the data being an array.
The year and genre arrays are coming directly from the jquery drop down menu. It is selected like by it's #id like so "$("#yearFilter")". This is the select form element.
<select multiple="multiple" name="yearFilter[]" class="filterChange" id="yearFilter">
What I need at the base level is:
var someData = "";
if(...){
someData = { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() };
}
else if(...){
someData = "sampleString";
}
And in ajax call:
...
data: someData,
...
I think I have an idea what you want but post has been overly complicated by extraneous issues like json stringify . Here's a function that could be used in several places eleswhere in your code to make one type of AJAX call or another.
You would then perhaps have several buttons and call the function within handlers for each type of button and change the argument passed to function
doAjax('someval');/* use in button 1*/
doAjax('someOtherval');/* use in button 2*/
function doAjax(arg) {
var someData = "";
if (arg == 'someval') {
someData = {
"yfilter": $("#yearFilter").val(),
"gfilter": $("#genreFilter").val()
};
} else {
someData = "sampleString";
}
$.ajax({
type: "POST",
url: "somefile.php",
cache: false,
data: someData,
dataType: "json",
success: function(data) {
if (arg == 'someval') {
alert("success 1");
} else {
alert("success 2");
}
}
})
}
Hope I've understood what you're asking for.
You could do something like this:
var parameters = {};
if (...) {
parameters = $("#yearFilter").serializeArray();
}
if () {
parameters = $("#genreFilter").serializeArray();
}
and then replace the line:
parameters: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
with:
data: parameters,
JSON type should be best option for dynamically data. push whatever data you wish to inside json like shown below, Hence create your json dynamically and send as ajax data.
var employees = {
accounting: [],
dept: "HR"
};
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
$.ajax({
url: POSTURL,
type: 'POST',
dataType: 'json',
data : employees,
contentType: 'application/json; charset=utf-8',
success: function (results)
{
},
error: function (results)
{
jQuery.error(String.format("Status Code: {0}, ", results.status, results.statusText));
}
});
Try it:
someData = JSON.stringify({ yfilter: $("#yearFilter").val(), gfilter: $("#genreFilter").val() });
It will work.

Resources