ajax post data is null in controller asp.net mvc 5 - c#

I try to send a JSON object back to the server. This is my AJAX call
function SaveData() {
var model = []
debugger
$.each($('.Money'), function (i, item) {
model.push({
Money: $('.Money').eq(i).val(),
Day: $('.Day').eq(i).val(),
Note: $('.Note').eq(i).val()
});
})
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: { partnerDeposit: JSON.stringify(model) },
type: 'POST',
dataType: 'json',
succsess: function () {
}
})}
This is the method in the controller which is being called:
enter image description here
https://i.stack.imgur.com/FqEt9.png
The problem I have is that always the json variable from above is an empty object. The success function gets called but when I debug the json var is displayed as empty.
Please tell me what I am doing wrong. Thank you.

Try adding the partnerDeposit to the JSON.stringify call like this:
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: JSON.stringify({partnerDeposit: model}),
type: 'POST',
dataType: 'json',
succsess: function () {
}
})

I haven't found this answer anywhere else so I had to discover it through experimentation. Hopefully this will help someone.
You'll find that in your controller, it's receiving a Request.Form object and if you look in Request.Form[0] you'll find your data. The reason that there's data in the form but MVC is seeing it as null is that the key to the form element being POSTed is "" (blank).
So client side, you have to set content type properly, and precede your data with something like "myData=" + JSON.stringify(myJSONObject), where "myData" is the key name you are adding, like so:
$.ajax({
type: "POST",
url: URL,
data: "myData="+JSON.stringify(myJSONObject),
contentType: "application/x-www-form-urlencoded; charset=utf-8"
On the server side, your [HttpPost] endpoint has to have as its input a variable with the same name as the key you declared in your AJAX, like so:
`
[HttpPost]
[Authorize]
public ActionResult Index (string myData) // <-- var name matches AJAX
{
// de-serialize data into server-side object using
// JSONConvert.DeserializeObject
}
`

Related

MVC Single String JSON post always coming Null in Controller

I am facing a strange problem in my MVC 5 application where I want to pass a Drop Down Selected value to controller using a Ajax post.
the Post code looks like this:
$(function () {
//Change the Value stream list each time the BU is selected
$('#Lob').change(function () {
alert(JSON.stringify($('#Lob option:selected').text()));
$.ajax({
url: '#Url.Content("~/Dashboard/GetValueStreams/")',
dataType: 'json',
type: 'POST',
data: JSON.stringify($('#Lob option:selected').text()),
contentType: 'application/json',
success: function (VSList) {
// do stuff
});
}
});
});
});
The ALERT works fine and displays the selected value correctly. However in the controller, the string appears as null.
[HttpPost]
public ActionResult GetValueStreams(string BUName)
{
// Here the BUName parameter is coming as null.
}
I have tried changing my JSON POST data to the following:
data: {"BUName": JSON.stringify($('#Lob option:selected').text())},
This also does not work. Any help will be much appreciated. Thanks.
Change your data to data: JSON.stringify({BUName : $('#Lob option:selected').text()}).
I tested and it worked.
$.ajax({
url: '#Url.Content("~/Dashboard/GetValueStreams/")',
dataType: 'json',
type: 'POST',
data: JSON.stringify({BUName : $('#Lob option:selected').text()}),
contentType: 'application/json',
success: function (VSList) {
// do stuff
}
});

Ajax call to MVC controllers

I'm trying to pass some data with ajax call to a c# mvc controller. Even though the task should be straight forward, I am unable to get the mvc controller to read the data I'm passing through the ajax call....
I've implemented the following code within my MVC controller
[HttpPost]
public string tt(string o)
{
return o;
}
[HttpPost]
public string tt2(string o)
{
return "lala";
}
And I'm triggering the following ajax calls from the browser
$.ajax({
url: "/Home/tt2",
type: "POST",
contentType: "application/json;",
data: JSON.stringify({ o: 'asdas'}),
success: function(e){console.log(e+' correct');},
error: function(e){console.log(e+' incorrect');}
});
$.ajax({
url: "/Home/tt",
type: "POST",
contentType: "application/json;",
data: JSON.stringify({ o: 'asdas'}),
success: function(e){console.log(e+' correct');},
error: function(e){console.log(e+' incorrect');}
});
As a result when running the first ajax call the result is
lala correct
And for the second ajax call, the result is
undefined correct
In the mean time these are some stuff I tried
Adding dataType: "json", to the ajax call
Changing the string data from {o: 'asdas'} to 'asdas'
Removing the JSON.stringify
Adding the charset=utf-8 to the contentType
Changing the ajax call type and MVC controller method from POST to GET to PUT
Changing the MVC controller method parameter from string to int
Removing the error method from the ajax call
Changing the data from data: {o: 'asdas'} to data: {"o":"asdas"}
Changing the data from data: {"o":"asdas"} to data: JSON.stringify({"o":"asdas"})
I know that simple string or int can be passed through the URL as query strings but it would be an issue when passing a list of objects..
Something aside is that the call is being done correctly to the URL because when I set a breakpoint within the called method, it does get triggered but the parameter always is null..
Any thoughts on how to make ajax call work?
try:
[HttpPost]
public string tt([FromBody]string o)
{
return o;
}
Your request should be like this:
$.ajax({
url: '#Url.Action("tt", "Home")',
data: {
"o": "asdasdas"
},
cache: false,
type: "POST",
success: function (response) {
},
error: function (xhr) {
}
});

AJAX post data is null when it reaches the ASP.NET Core 2.1 controller

I'm posting data to an ASP.NET Core MVC 2.1.2 page using this jQuery code:
function OnCountryChange() {
$.ajax({
url: "/OnCountryChange",
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
headers: {
"RequestVerificationToken": $('input[name = __RequestVerificationToken]').val()
},
data: JSON.stringify({
sCountryCode: "Test 123"
})
});
}
I am receiving the post in the controller with this method:
[HttpPost]
[ValidateAntiForgeryToken]
[Route("/OnCountryChange")]
public IActionResult OnCountryChange([FromBody] string sCountryCode)
{
logger.LogDebug($"Country code is: {sCountryCode ?? "null"}");
return Json(sCountryCode);
}
The output printed to the log is:
Country code is: null
The raw request body (viewed using Fiddler) looks like this:
{"sCountryCode":"Test 123"}
Why isn't the data being passed?
I am not familiar with C#,but in your question you have add
contentType: "application/json; charset=utf-8"
in your Ajax method which means the data parameter is json format,so you need to access as json object instead of access string directly.
Two ways to solve it:
a. Change your C# controller method to access like a json object
b. Send Ajax parameter without json,code similar to below:
function OnCountryChange() {
$.ajax({
url: "/OnCountryChange",
type: "POST",
datatype: "json",
headers: {
"RequestVerificationToken": $('input[name = __RequestVerificationToken]').val()
},
data: {sCountryCode: "Test 123"}
});
}

Asp.net MVC: controller with first parameter as json and second parameter as string from View

We have a situation where we would like controller to get First parameter as json (model) as second parameter as some additional data other than model (such as Flag, source control from where event is driven etc.), we have tried tweaking with jQuery but all ended up error shown in the browser inspect element.
We have our controller typically like this:
public async Task<ActionResult> Foo(Bar b, string additionaldata)
{
if (additionaldata="Deleted")
{
}
else if (additionaldata="Favorite")
{
}
}
And inside view its something like this:
$("#delete").click(function () {
$.ajax({
url: "/Index/Foo",
type: "POST",
data: $("#myform").serialize(),
dataType: "json"
}).done(function (model) {
$("#Foo_Id").val(model.Foo.Id);
});
});
As far as model is concerned, this jQuery is working fine, but as far as we try to add some additional parameter, we are clueless.
Please suggest how we may pass it.
On option is to use FormData to build the model and add additional data
var formdata = new FormData($('#myform').get(0)); // serialize the form
formdata.append('additionaldata', 'Favorite'); // add additional properties
$.ajax({
url: '#Url.Action("Index", "Foo")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});

MVC3 Controller not receiving any parameter values

Using JQuery, I am passing values to an action in the controller. customerId and productId are not null:
$.ajax({
type: "GET",
url: "Customer/Product/",
data: { Customer: customerID, Product: productId},
dataType: "json",
error: function (xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
$("#productName").innerHTML = json;
alert(json);
alert($("#startDate").innerHTML);
}
});
In MVC3 controller, i have the action:
public ActionResult Product(string Customer, string Product)
{
//both are null
}
I don't know why both are null? Please guide
$.ajax({
type: "GET",
url: "Customer/Product/",
data: "Customer="+customerID +"&Product="+productId,
dataType: "json",
error: function (xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
$("#productName").innerHTML = json;
alert(json);
alert($("#startDate").innerHTML);
}
});
Try this way.
MVC may be expecting a JSON string. Try using this as your data
data: JSON.stringify({ Customer: customerID, Product: productId})
If you change it to a "POST" request it should work.
However it looks like you are actually trying to just "GET" data from the server which should really be encoded in your URL e.g. mysite.com/Customer/{customer_id}/Product/{product_id}. In this case you'll probably need to change your routing rules.
I just did "File -> New Project" and just added the one controller and tried directly using:
var customerID = 42;
var productId = 4242;
$.ajax({
type: "GET",
url: "http://localhost:51622/Customer/Product",
data: { Customer: customerID, Product: productId},
dataType: "json",
error: function (xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
console.log(json);
}
});
It binds the values just fine, so you might want to grab fiddler or something similiar and make sure that you are actually sending values to the server.

Categories