Data from ajax post is passing null to the controller - ajax

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.

Related

Parameters not populating with Ajax Call

This is my controller
[HttpPost]
public bool Sync(int? id, string name)
{
throw new NotImplementedException();
}
Here is my ajax request call that I am trying to make to this controller:
<script type="text/javascript">
var buttonClicked = document.getElementById("syncLegacy");
buttonClicked.addEventListener('click', function () { syncLegacyMake(); }, false);
function syncLegacyMake() {
$.ajax({
url: '/Legacy/Sync',
type: 'POST',
data: JSON.stringify({
id: $("#Id").val(),
name: $("#Name").val()
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
},
error: function () {
alert("error");
}
});
}
The controller gets hit however there are no values to the parameters. The values are both null.
When I look at the call itself on chrome console, the values are populated as these under Request Payload in the headers:
{id: "01", name: "Titan"}
id
:
"01"
name
:
"Titan"
Could anyone point out what I am doing wrong here? I have been able to do the same in .net 4.6.1 framework so not sure if framework changed has caused this?
have you tried the following things:
Using a Dto instead of separate simple types:
public class SyncDto
{
public int? Id {get;set;}
public string Name {get;set;}
}
// Controller action:
[HttpPost]
public bool Sync(SyncDto input)
{
throw new NotImplementedException();
}
Make Jquery stringify itself
Let jquery figure your ajax call out itself:
$.ajax({
url: '/Legacy/Sync',
type: 'POST',
data: {
id: $("#Id").val(),
name: $("#Name").val()
}
});

Render partial view with AJAX-call to MVC-action

I have this AJAX in my code:
$(".dogname").click(function () {
var id = $(this).attr("data-id");
alert(id);
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'html',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
});
});
The alert gets triggered with the correct value but the AJAX-call does not start(the method does not get called).
Here is the method that im trying to hit:
public ActionResult GetSingleDog(int dogid)
{
var model = _ef.SingleDog(dogid);
if (Request.IsAjaxRequest())
{
return PartialView("_dogpartial", model);
}
else
{
return null;
}
}
Can someone see what i am missing? Thanks!
do you know what error does this ajax call throws?
Use fiddler or some other tool to verify response from the server.
try modifying your ajax call as following
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'string',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
error: function(x,h,r)
{
//Verify error
}
});
Also try
$.get("Home/GetSingleDog",{dogid : id},function(data){
$('#hidden').html(data);
});
Make sure, URL is correct and parameter dogid(case sensitive) is same as in controller's action method

How do I POST collection of data to controller action

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

MVC 5 Ajax POST - action variable not recognizing ajax data variable

I have a click function that grabs rows from an grid. The return value is a list of objects which represent each row. I use JSON.stringify so I can send the data to my SaveJobs action on my Home Controller. The following properties work and my controller action recognizes the data, but it is not in valid JSON format.
contentType: 'application/json; charset=utf-8'
data: { data: JSON.stringify(editedRows) }
However, I found through research that the below method is preferred since it is a valid JSON format, but my data variable on my controller action is null (returning no data to perform my action on) and I could not debug the issue. Why does the action variable not recognize this? Thank you.
$('#SaveJobs').on('click', function () {
editedRows = getEditedRows();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: savePlannedJobsUrl,
cache: false,
data: JSON.stringify({ data: editedRows }),
dataType: "text",
success: function (result) {
if (result === 'Success') {
alert('The records you have edited are saved');
}
else {
alert('There was an error with the server. All records may not have been saved.');
}
$("*").css("cursor", "");
},
error: function (HtmlHttpRequest, ajaxOptions, thrownError) {
var htmlObj = $.parseHTML(HtmlHttpRequest.responseText);
var savedJson = JSON.stringify(editedRows);
if (htmlObj !== null) {
var htmlBody = htmlObj[htmlObj.length-1].outerText;;
}
tryToWriteError(htmlBody, savedJson);
}
});
return false;
});
Controller
[HttpPost]
public string SaveJobs(string data)
{
// CODE HERE
}
ANSWER:
I marked #Queti's answer, and more specific to my problem see the link in my comment that will help for MVC projects. That resolution will skip creating DTOs.
The issue is that you are sending in an array of objects, but your action method is expecting a string.
It appears that your getEditedRows method is returning an array of objects.
I recommend you create a model on the server that matches what you are passing in. Something like:
public class MyDto
{
int id { get; set; }
string comments { get; set; }
}
And then update your method signature to accept that as the parameter:
public string SaveJobs(List<MyDto> data)

MVC3 jquery ajax parameter data is null at controller

I have a controller action that I want to update via a jquery call. The action runs, but there is no data in the parameters.
I am using a kedoui grid with a custom command in a column that I want to run some server code.
kendoui grid in view
...
columns.Command(command =>
{
command.Custom("ToggleRole").Click("toggleRole");
});
...
The model is of type List<_AdministrationUsers>.
public class _AdministrationUsers
{
[Key]
[ScaffoldColumn(false)]
public Guid UserID { get; set; }
public string UserName { get; set; }
public string Role { get; set; }
}
Here is my toggleRole Script:
<script type="text/javascript">
function toggleRole(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
alert(JSON.stringify(dataItem));
$.ajax({
type: "POST",
url: '#Url.Action("ToggleRole", "Administration")',
data: JSON.stringify(dataItem),
success: function () {
RefreshGrid();
},
error: function () {
RefreshGrid()
}
});
}
</script>
Here is my controller action:
[HttpPost]
public ActionResult ToggleRole(string UserID, string UserName, string Role)
{
...
}
The controller action fires, but there is no data in any of the parameters.
I put the alert in the javascript to verify that there is indeed data in the "dataItem" variable. Here is what the alert text looks like:
{"UserID":"f9f1d175...(etc.)","UserName":"User1","Role","Admin"}
Did you try specifying the dataType and contentType in you ajax post ?
$.ajax({
type: "POST",
url: '#Url.Action("ToggleRole", "Administration")',
data: JSON.stringify(dataItem),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
RefreshGrid();
},
error: function () {
RefreshGrid()
}
});
It looks like you are posting the whole object as one Json string, while the controller expects three strings. If you are using MVC3 the parameter names also have to match the controllers signature. Try to parse up your data object so that it matches the input expected from the controller. Something like this:
$.ajax({
type: "POST",
url: '#Url.Action("ToggleRole", "Administration")',
data: { UserID: dataItem.UserID, UserName: dataItem.UserID, Role: dataItem.Role },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
RefreshGrid();
},
error: function () {
RefreshGrid()
}
});
Hope that helps!
{"UserID":"f9f1d175...(etc.)","UserName":"User1","Role","Admin"}
Seems incorrect to me. Wouldn't you want this?
{"UserID":"f9f1d175...(etc.)","UserName":"User1","Role" : "Admin"}
Notice the "Role" : "Admin"

Resources