MVC Single String JSON post always coming Null in Controller - c#

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
}
});

Related

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"}
});
}

Setting data filters in partial views

I need a little help.
So I'm trying to call a lot of partial views from the same list model, each using a different filter. Is there anyway for me to pass the Datafilter value from the views into the model?
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "ControlerFolder/Controler",
data: {someParameter(Filter): "value"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
msg is the json that you can return
}
});
});
});
If you need more help say something.

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

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
}
`

Ajax URL - Incorrect .net #c

Been following some tutorials, as i'm learning C#, however was just attempting to make an ajax call to the server, i'm using my localhost.
As far as I can tell i'm doing its right, but it's obviously not.
Maybe it my folder structure or just the name of the file.
The Default.aspx file is at the project root
Here is my ajax call
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx",
dataType: "json",
data: "{'FirstName':'test','LastName':'test1','City':'test3','EmailID':'test4'}",
success: function (data) {
console.log("Woo!");
},
error: function (result) {
console.log("fail!");
}
});
I know eventually it will have to call a method within the file, but its not even finding it at the moment.
Thanks in advance, James
You can use controller Home and create the one action.
Example:
public ActionResult FirstAjax()
{
return Json(true, JsonRequestBehavior.AllowGet);
}
After that your jquery ajax is:
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "Home/FirstAjax",
dataType: "json",
data: "",
success: function (data) {
console.log("Woo!");
},
error: function (result) {
console.log("fail!");
}
});

How to send and retrieve data from web method using JQuery Ajax Call? [duplicate]

This question already has answers here:
Send JSON data via POST (ajax) and receive json response from Controller (MVC)
(8 answers)
Closed 9 years ago.
I have a text box and a button next to it. I want to send the content of textbox through Jquery ajax call to webmethod and get back the upper case value of the same and display that in alert. So far i have this code but its not working.
JAVASCRIPT:
function CallWM()
{
var name = $('#name').val();
RealCallWM(name);
}
function RealCallWM(name) {
$.ajax({
url: 'Register.aspx/UpperWM',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: { name: JSON.stringify(name) },
success: OnSuccess(response),
error: function (response) {
alert(response.responseText);
}
})
};
HTML:
Name: <input id="name" type="text" />
<input id="Button1" type="button" value="button" onclick="CallWM();"/></div>
</form>
WEB METHOD:
[WebMethod]
public static string UpperWM(string name )
{
var msg=name.ToUpper();
return (msg);
}
Replace:
data: '{name: ' + name + '}',
with:
data: { name: JSON.stringify(name) },
to ensure proper encoding. Right now you are sending the following payload:
{name:'some value'}
which is obviously an invalid JSON payload. In JSON everything should be double quoted:
{"name":"some value"}
That's the reason why you should absolutely never be building JSON manually with some string concatenations but using the built-in methods for that (JSON.stringify).
Side note: I am not sure that there's a callback called failure that the $.ajax method understands. So:
$.ajax({
url: 'Register.aspx/UpperWM',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: { name: JSON.stringify(name) },
success: OnSuccess(response),
error: function (response) {
alert(response.responseText);
}
});
Also notice that in your error callback I have removed the response.d property as if there's an exception in your web method chances are that the server won't return any JSON at all.
As per your comment I understood your issue not yet resolved, so just try this
function RealCallWM(name) {
$.ajax({
type: "POST",
url: "Default.aspx/UpperWM",
data: JSON.stringify({ name: $('#name').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}

Categories