Receiving object properties are null on server after an ajax put request - javascript

I've a problem with sending data form the browser to an API on my server by an ajax request to the server (method is PUT). Here is my JavaScript code:
var json = JSON.stringify({
StemType: {
ID: parseInt(this.dataset.id),
Type: this.dataset.type,
GebruikerID: "#(Model.DeTopic.Gebruiker.Id)"
},
Punten: parseInt(this.dataset.punten),
GestemdeGebruikerID: "#(Model.AangemeldeGebruiker)"
});
$.ajax({
url: "../Stem/Toevoegen",
type: "PUT",
data: json,
success: function (returnData) {
// my code
}
});
This is the json code in the variable json:
{
"StemType": {
"ID": 24731,
"Type": "Topic",
"GebruikerID": "539e6078"
},
"Punten": 1,
"GestemdeGebruikerID": "3aedefab"
}
And here is the C# code on the server.
public class StemController : ApiController
{
[HttpPost]
[Authorize]
[Route("Stem/Toevoegen")]
public void Toevoegen([FromBody]Stem stem)
{
Console.WriteLine(stem.ToString());
}
}
Here is the class Stem:
public class Stem
{
public StemType StemType { get; set; }
public int Punten { get; set; }
public string GestemdeGebruikerID { get; set; }
}
public class StemType
{
public int ID { get; set; }
public Type Type { get; set; }
public string GebruikerID { get; set; }
}
But if I debug my code on the server, I've got this:
Can anyone help me?

I've found two possible ways:
Don't stringify it for send as an object.
Add contentType: "application/json" for Json code.

Related

List of Objects and Id not getting passed to MVC Controller Method Using jQuery Ajax

Im trying to pass an Id and object of picList to the controller and it shows up null. I've looked at all the other SO solutions and changed my code to what they said and Im still getting null for both values in the controller.
So I've even tried to change the data that is being sent to the controller as such to see if that made any difference and it didn't.
in ajax call i changed the data to such
data: {"Name": "Adam"},
and added this to the controller and still nothing is getting passed.
UnitImages(string Name,..
here is what the JSON.stringify(data) looks like.
View Model
public class FileViewModel
{
public FileViewModel()
{
UnitPicturesList = new List<UnitPictures>();
}
public IList<IFormFile> Files { get; set; }
[Required]
public int AuctionId { get; set; }
public string FileLocation { get; set; }
public List<UnitPictures> UnitPicturesList { get; set; }
}
model
public class UnitPictures
{
public long ImageId { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
public int SortOrder { get; set; }
}
controller
[HttpPost]
public ActionResult UnitImages(long auctionId, List<UnitPictures> picList)
{ ...
}
Ajax call
function UpdateImages(auctionId, picList) {
var data = { auctionId: auctionId, picList: picList };
console.log(JSON.stringify(data));
$.ajax({
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
url: '/PhotoUploader/UnitImages',
data: JSON.stringify(data),
success: function(data){
if(data.Result == 1) {
alert("images where successfully updated.");
}else {
alert('images where successfully updated.');
}
},
error: function() {
alert("The images were not updated because of a problem.")
}
});
}
Asp.net core MVC default binding value from form, Here you can try to add [FromBody] attribute on your parameter to change the resource to bind value from body.
[HttpPost]
public ActionResult UnitImages([FromBody]string Name)
{ ...
}
Model details you can refer to Model Binding.
Try using a class that match the posted model. Something like this:
public class UnitPictures_ViewModel
{
public int AuctionId {get;set;}
public List<UnitPictures> PicList { get; set; }
}
public class UnitPictures
{
public long ImageId { get; set; }
public string FileName { get; set; }
public string FileLocation { get; set; }
public int SortOrder { get; set; }
}

How to forward list containing js objects to asp.net core mvc?

I generate the js object, which looks as follows:
cartStorage = {
name: 'testcustomer',
email: 'test#gmail.com',
items: [
{
licenseName: 'Private',
licensePrice: 2
},
{
licenseName: 'Public',
licensePrice: 4
}
],
totalPrice: 6
}
Then I pass this object to mvc controller using ajax
$.ajax({
url: '/TestPayment/ChargeTest',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(cartStorage),
success: function(response){
if (response != null) {
alert(response);
} else {
alert("Something went wrong");
}
}
});
Here's the viewmodel associated with this method
namespace Web.ViewModels.Payment
{
public class Items
{
public string licenseName { get; set; }
public int licensePrice { get; set; }
}
public class PayerInfo
{
public int totalPrice { get; set; }
public string name { get; set; }
public string email { get; set; }
public Items Items { get; set; }
}
}
Here's the mvc controller method, which processes the ajax request
[HttpPost]
public ContentResult ChargeTest([FromBody] PayerInfo model)
{
String FullName = model.name;
}
But when the server executes the controller method, the model turns out to be null.
However, if I comment out the Items class and the instance creation in the PayerInfo class in the viewmodel, then the model is being forwarded successfully and all the data is stored, I'm just having the problem with the list inside of js object.
What am I doing wrong?
items in your json object is a list. So you need to change the type of Items in your c# model to a list.
namespace Web.ViewModels.Payment
{
public class Items
{
public string licenseName { get; set; }
public int licensePrice { get; set; }
}
public class PayerInfo
{
public int totalPrice { get; set; }
public string name { get; set; }
public string email { get; set; }
public List<Items> Items { get; set; }
}
}

Can not get value by ajax query

I using .net core. Have this class:
public class SentEmailItem
{
public SentEmailItem()
{
Attachments = new List<AttachmentItem>();
}
public long PKID { get; set; }
public string EmailTo { get; set; }
public string EmailFrom { get; set; }
public string Cc { get; set; }
public string Bcc { get; set; }
public string Body { get; set; }
public string Subject { get; set; }
public List<string> EmailToList => EmailTo.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
public List<string> CcList => (Cc ?? string.Empty).Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
public List<string> BccList => (Bcc ?? string.Empty).Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
public List<AttachmentItem> Attachments { get; set; }
}
And this method in controller:
[HttpPost]
public JsonResult SendEmail(SentEmailItem item)
{
EmailHelper.SendEmailAsync(item);
return SuccessJsonResult();
}
But when called this method from ajax by this code:
$.ajax({
type: "POST",
url: self.sendEmailUrl,
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ item: emaiItem })
}).done(function (json) {
App.unblockUI();
if (json.HasErrors) {
var errorsHtml = $.map(json.Errors, function (x) { return "" + x.ErrorMessage + "<br/>"; }).join("");
UIToastr.ShowMessage('error', 'Error', errorsHtml);
return;
}
self.sendEmailCompleted(json);
});
I can't get data in my controller method. All data have null value. But in emaiItem placed in js value looks like:
Bcc : "Testmail#mail.com"
Body : "test body"
Cc : "Testmail#mail.com"
EmailFrom : "just3f#mail.com"
EmailTo : "Testmail#mail.com"
Subject : "Test subject"
It seems like emaiItem is already an object like this -
var emaiItem = {Bcc : "Testmail#mail.com",
Body : "test body",
Cc : "Testmail#mail.com",
EmailFrom : "just3f#mail.com",
EmailTo : "Testmail#mail.com",
Subject : "Test subject"};
If so, it could just use JSON.stringify(emaiItem). Otherwise, you can hard-code the above emaiItem, and see those values populated at server-side.
$.ajax({
...
data: JSON.stringify(emaiItem)
}).done(function (json) {
...
});
Solution
Replace with JSON.stringify(emaiItem), and use [FromBody] attribute to force model binder to bind data from the request body.
[HttpPost]
public JsonResult SendEmail([FromBody]SentEmailItem item)
{
}
Have you tried debugging your c# code to see if the back-end api is being hit? That would be a good place to start if not.

Nested JSON values not binding MVC

I have a game object in client side JavaScript that looks like this right before being sent to the server:
Here it is server side a second later, note all the properties are filled, and the Questions list is populated with the correct number of question, however the properties of each question are null, whereas on the client side they had the correct values.
Here is the code for the models:
public class Game
{
public Game()
{
Questions = new List<Question>(5);
}
public int GameID { get; set; }
public Guid UserID { get; set; }
public Guid CurrentGameID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IEnumerable<Question> Questions { get; set; }
}
public class Question
{
public int ID { get; set; }
public string Text { get; set; }
public IEnumerable<int> Answers { get; set; }
public int SelectedAnswer { get; set; }
}
And here is how I send the object back to the server:
// Send completed game back to server
$.post("Games/CompleteGame", currentGame, function (results)
{
// display results to user
}
Based on Ek0nomik's comment asking about the content-type, I rewrote my ajax call to set contentType to json:
$.ajax(
{
url: "Games/CompleteGame",
type: "POST",
data: JSON.stringify(currentGame),
contentType: "application/json",
success: function (results)
{
// show results to user...
}
As it turns out, this was all it needed to make it work.

Jquery ASMX Web Service call - send / receive complex types

Not sure if it's just the time of day, lack of coffee or over indulgence of sugar from last night. Besides that I'm trying to get this working. I do not want to change / modify / add a new web service method.
I have an asmx web service:
public UserLogin Login(UserLogin p_objUserLogin)
{
}
I need to hook a JQuery ajax call up to that. The UserLogin object is not that complex:
public class UserLogin
{
public UserLogin();
public string Privileges { get; set; }
public string ClientCodeID { get; set; }
public UserDetails User { get; set; }
public string UserLoginMessage { get; set; }
public bool Valid { get; set; }
}
The UserDetails object is quite large, and includes a lot more data. (Hopefully I don't need to build the entire object tree to get this to work).
public class UserDetails
{
public string CellPhone { get; set; }
public string Email { get; set; }
public string EncryptedPassword { get; set; }
public string FirstName { get; set; }
public string FullName { get; }
public string Initials { get; set;
public bool InService { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public byte[] Signature { get; set; }
public string SimCard { get; set; }
public int UserID { get; set; }
public string UserName { get; set; }
public SecurityRole UserSecurityRole { get; set; }
public Workgroup UserWorkgroup { get; set; }
}
The script I'm playing around with:
function CallService() {
var p_objUserLogin = {};
p_objUserLogin['ClientCodeID'] = "Test";
var DTO = { 'p_objUserLogin': p_objUserLogin };
$.ajax({
type: "POST",
url: "UtilityServices2006.asmx/Login",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (msg) {
alert(msg);
},
error: function (req, status, error) {
alert(req + ", " + status + ", " + error);
},
complete: function (req, status) {
alert(req + ", " + status);
}
});
}
Any help would be quite amazing.
Ensure your webservice class and method are decorated to handle incoming ajax/json requests:
[ScriptService]
public class MyService: WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public UserLogin Login(UserLogin p_objUserLogin)
{
}
}
I'm not familiar with the notation you're using to configure your payload object (p_objUserLogin['ClientCodeID'] = "Test";). I've usually used slightly different notation:
p_objUserLogin.ClientCodeID = 'Test';
However, that might be a red herring - I'm not a JS-objects expert, so your notation may be perfectly valid.
Finally, I'm not sure if JS will automatically convert your object to JSON (var DTO = { 'p_objUserLogin': p_objUserLogin };). I use the json2 library to explicitly serialize JS objects to JSON:
var DTO = { 'p_objUserLogin': JSON.stringify(p_objUserLogin) };
Hope this helps you nail down the issue.

Categories