json string on POST to MVC action method using AJAX is null - javascript

I am getting a hard time to find out why the string sent via AJAX request is null. Console.WriteLine(data) shows empty. Status is 200 OK. If I add some code to parse the string received, I get an error stating that JObject.Parse cannot be null. I don't know what am I missing. The javascript code is ok. The action method also seems ok, but my knowledge on Asp.Net Core and MVC is very scarce, so I am not sure. Can someone please point out what am I missing?
The javascript code:
let obj = {email: email_address.value};
let objStringified = JSON.stringify(obj);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=UTF-8',
data: objStringified,
url: '#Url.Action("ReturnCheckAccountDuplication")',
dataType: 'text',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("Keep trying", error);
}
});
C# code:
[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] string data)
{
Console.WriteLine(data);
JObject jObject = JObject.Parse(data);
string email = (string)jObject["email"];
bool emailExists = CheckAccountDuplication.Get(email);
string returnResult = emailExists.ToString();
return Content(returnResult);
}
The solution on the controller side is
public class AccountCheckModel
{
public string Email { get; set; }
}
[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)
{
string result = CheckAccountDuplication.Get(data.Email).ToString();
return Content(result);
}
Thanks to all the members who commented on my problem, especially John Glenn who provided a solution. I had been trying for several days but without success. My knowledge of Asp.Net Core is very poor indeed. Thank you very much.

The easiest solution is to create a model representing the JSON data that your controller will receive. For example, create a class like so:
public class AccountCheckModel
{
public string email { get; set }
}
Then, use it as the parameter for your controller method:
public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)
This is the preferred way to access the request body. To get the request body as a string, you have to jump through some serious hoops.

An alternative way to send your data via AJAX to your Controller:
var json = {
email: email_address.value
};
$.ajax({
type: 'POST',
data: {'json': JSON.stringify(json)},
url: '#Url.Action("ReturnCheckAccountDuplication")',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("Keep trying", error);
}
});
And your Controller:
[HttpPost]
public ActionResult ReturnCheckAccountDuplication(string json)
{
Console.WriteLine(json);
JObject jObject = JObject.Parse(json);
string email = (string)jObject["email"];
bool emailExists = CheckAccountDuplication.Get(email);
string returnResult = emailExists.ToString();
return Content(returnResult);
}

Related

Access form data in C# controller from AJAX post

I am sending form data to a c# controller using AJAX, however I don't know how to access the data inside the controller. I am trying to pass the form data into the controller as a Person object but I am just returning system.Models.Person. I am new to C# so any help would be greatly appreciated, thanks a lot.
Javascript
$('#myForm').submit(function(e){
e.preventDefault();
const formData = new FormData(e.target);
$.ajax({
url: '/Home/GetFormData',
type: 'POST',
data: {formData: formData},
success: function(resultData){
console.log(resultData)
},
error: function(){
//do something else
}
})
}
Model
public class Person
{
public string name { get; set; }
public string age { get; set; }
}
Controller
public string GetFormData(Person formData)
{
string name = formData.name.ToString();
return name;
}
The following post will help you
Post Data Using jQuery in ASP.NET MVC
Your code should be
Model class Person.cs
public class Person
{
public string name { get; set; }
public string age { get; set; }
}
jQuery function to get the form data, I am assuming here you have submit button on your form
$(document).ready(function () {
$("#btnSave").click(function () { //Your Submit button
$.ajax(
{
type: "POST", //HTTP POST Method
url: "Home/GetFormData", // Controller/View
data: { //Passing data
name: $("#txtname").val(), //Reading text box values using Jquery
age: $("#txtage").val(),
}
});
});
});
Your HomeController method
[HttpPost]
public ActionResult GetFormData(Person obj)
{
string name = obj.name;
string age = obj.age;
//Once you have data here then you can pass anywhere i.e. database or some other method
return View();
}
Form values in the controller
Let me know, if any clarification required.
Use serialize if you will send form values:
$form = $(this).serialize();
Use FormData if you be sending a file for upload and alike.
And on your data declaration, set it as is (without declaring it as a literal JS object)
data: $form
The final code would look like this:
$('#myForm').submit(function(e){
e.preventDefault();
$form = $(this).serialize();
$.ajax({
url: '/Home/GetFormData',
type: 'POST',
data: $form,
success: function(resultData){
console.log(resultData)
},
error: function(){
//do something else
}
})

ASP.NET: Ajax doesn't send string

I have this method to send some data with ajax:
function SendData(foodID, basketID) {
var data = { FoodID: foodID, BasketID: basketID };
$.ajax({
url: '/Order/Post',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json;utf-8',
datatype: 'json'
}).done(function (data) {
console.log(data);
}).fail(function (data) {
console.log("Error: " + data);
});
}
In C#, my Post Method in my Order controller gets triggered, but the string I want to hand over is null:
public bool Post(string s)
{
//When this gets executed, s is null
return true;
}
I tested this by executing SendData(1,1) directly on a button click. What is the mistake I'm doing and how can I get the string in my Post-Method?
you are post the object. not string.
you can try generate to object and load this object. or add new one parameter to action (foodId and basketId but you must post like that if you check this option data:{foodId,basketId})
//model
public class SomeObject{
public string FoodId {get;set;}
public string BasketId {get;set;}
}
//code
public bool Post(SomeObject data)
{
return true;
}
It seems for me your data structure to the Post action doesn't match action parameter names. Try this:
[HttpPost]
public bool Post(string foodID, string baskedID)
{
return true;
}
I believe you have to name your data that's being passed like so:
data: { 's': JSON.stringify(data) }

Ajax sending Null to .net core MVC controller and unsure why

I am very new to Ajax and for me it's something I can't get my head around (well jQuery in general to be honest).
I am trying to pass an object containing two string arrays, one of search parameters, another of search values.
The issue, is that when i press the submit button, the Ajax call hits the MVC controller but the Model in the Controller returns Null in both arrays.
The Ajax call:
function onActivation() {
var send = { queryParameters: queryParameters, queryValues: queryValues };
$.ajax({
url: '#Url.Action("Index", "SearchResults")',
type: "POST",
contentType: "application/json; charset=utf-8;",
data: JSON.stringify({ advancedSearch: send }),
success: function (response) {
response ? alert("It worked!") : alert("It didn't work.");
}
});
}
The Model:
public class AdvancedSearch
{
public string[] queryParameters { get; set; }
public string[] queryValues { get; set; }
}
The first line of the controller where things go wrong:
public async Task<IActionResult> Index(AdvancedSearch advancedSearch)
For this to work you need to submit the Ajax with just data: send. For the model data binding to happen you can try to add another parameter in Ajax which is traditional: true as suggested in
Send array via Ajax and bind to List<string> on MVC 4

Deserialize JSON into dictionary in Web Api controller

I have such JSON string:
'{"1":[1,3,5],"2":[2,5,6],"3":[5,6,8]}'
I want to send it to the Web Api Controller without changing using ajax request:
$.ajax({
type: "POST",
url: "Api/Serialize/Dict",
data: JSON.stringify(sendedData),
dataType: "json"
});
In Web Api I have such method:
[HttpPost]
public object Dict(Dictionary<int, List<int>> sendedData)
{
//code goes here
return null;
}
And always sendedData == null. Another words: I don't know how to deserialize JSON into (Dictionary<int, List<int>>.
Thank you for answer.
Try this
[HttpPost]
public object Dict(Dictionary<int, List<int>> sendedData)
{
var d1 = Request.Content.ReadAsStreamAsync().Result;
var rawJson = new StreamReader(d1).ReadToEnd();
sendedData=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>(rawJson);
}
You can send the data like this:
{"sendedData":[{"key":"1","value":[1,3,5]},{"key":"2","value":[2,5,6]},{"key":"3","value":[5,6,8]}]}
Image of the function in the controller:
Dict
Try it:
Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>("{'1':[1,3,5],'2':[2,5,6],'3':[5,6,8]}");
Try using:
public ActionResult Parse(string text)
{
Dictionary<int, List<int>> dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<int>>>(text);
return Json(dictionary.ToString(), JsonRequestBehavior.AllowGet);
}
This works when the sent data doesn't have quotes around the indices:
{1:[1,3,5],2:[2,5,6],3:[5,6,8]}
Also make sure that you send an object in the Javascript:
data: {
text: JSON.stringify(sendedData)
},
specify the content type parameter when performing ajax call, dataType is for return result:
$.ajax({
type: "POST",
url: "Api/Serialize/Dict",
contentType: "application/json; charset=utf-8", //!
data: JSON.stringify(sendedData)
});
You missed the [FromBody] annotation in the sendedData param. Try this:
[HttpPost]
[Consumes("application/json")]
[Produces("application/json")]
public object Dict([FromBody] Dictionary<int, List<int>> sendedData)
{
//code goes here
return null;
}

jQuery AJAX post to MVC Controller object -- request shows up null

I know I'm missing something in the details here.
Problem
Despite Googling, trying examples, different formats, etc, the AJAX request that I send always is validated as having all fields empty, but not being null.
I think I'm not sending things in the proper format for the controller to recognize it as an object but I'm not sure what.
Fiddler: What my request looks like
With some dummy data:
Code: Model Class
public class ContactUsMessage
{
public string Email { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string Message { get; set; }
}
Code: WebAPI Controller
[HttpPost]
public HttpResponseMessage NewMessage(ContactUsMessage messageToSend)
{
if (messageToSend == null)
{
var sadResponse = Request.CreateResponse(HttpStatusCode.BadRequest, "Empty Request");
return sadResponse;
}
var messageValidator = new ContactUsMessageValidator();
var results = messageValidator.Validate(messageToSend);
var failures = results.Errors;
var sadString = "";
if (!results.IsValid)
{
foreach (var error in failures)
{
sadString += " Problem: " + error.ErrorMessage;
}
var sadResponse = Request.CreateResponse(HttpStatusCode.NotAcceptable, "Model is invalid." + sadString);
return sadResponse;
}
else
{
SendContactFormEmail(messageToSend.Email, messageToSend.Name, messageToSend.PhoneNumber, messageToSend.Message);
}
Code: JavaScript on Page
function sendSubmissionForm() {
var dataObject = JSON.stringify(
{
messageToSend: {
'Email': $('#inpEmail').val(),
'Name': $('#inpName').val(),
'PhoneNumber': $('#inpPhone').val(),
'Message': $('#inpMessage').val()
}
});
$.ajax({
url: '/api/contactus/newmessage',
type: 'POST',
done: submissionSucceeded,
fail: submissionFailed,
data: dataObject
});
}
When you JSON.stringifyied your data object you converted it to JSON. But you forgot to set the Content-Type request header and the Web API has no way of knowing whether you are sending JSON, XML or something else:
$.ajax({
url: '/api/contactus/newmessage',
type: 'POST',
contentType: 'application/json',
done: submissionSucceeded,
fail: submissionFailed,
data: dataObject
});
Also when building the JSON you don't need to wrap it in an additional property that matches your method argument name. The following should work as well:
var dataObject = JSON.stringify({
'Email': $('#inpEmail').val(),
'Name': $('#inpName').val(),
'PhoneNumber': $('#inpPhone').val(),
'Message': $('#inpMessage').val()
});

Categories

Resources