I am sending a JSON through Ajax to a C# endpoint but it receives it empty, I have tried it with [FromBody] without success.
Javascript:
var settings = {
"url": "Configuracion/CreateTallas",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify({
"TalTalla": "XXS",
"TalFechaAlta": "2023-01-13T20:37:53.492Z",
"TalDescripcion": "Extra Chica",
"TalEstatus": 1
}),
};
$.ajax(settings).done(function (response) {
console.log(response);
});
C#:
public partial class UntCatTalla
{
public int TalId { get; set; }
public string TalTalla { get; set; } = null!;
public DateTime TalFechaAlta { get; set; }
public string? TalDescripcion { get; set; }
public bool TalEstatus { get; set; }
}
[HttpPost]
public IActionResult CreateTallas(UntCatTalla newTalla)
{
return Ok(_configs.CreateTallas(newTalla));
}
It is common to use [FromBody] attribute if the parameter you want to pass is JSON type.
In your case, you are passing incorrect data which causing the parameter to be empty. Change the value TalEstatus to true or false.
Try below codes
Javascript
var settings = {
"url": "Configuracion/CreateTallas",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify({
"TalTalla": "XXS",
"TalFechaAlta": "2023-01-13T20:37:53.492Z",
"TalDescripcion": "Extra Chica",
"TalEstatus": true
}),
};
$.ajax(settings).done(function (response) {
console.log(response);
});
C#
public partial class UntCatTalla
{
public int TalId { get; set; }
public string TalTalla { get; set; } = null!;
public DateTime TalFechaAlta { get; set; }
public string? TalDescripcion { get; set; }
public bool TalEstatus { get; set; }
}
[HttpPost]
public IActionResult CreateTallas([FromBody] UntCatTalla newTalla)
{
return Ok(_configs.CreateTallas(newTalla));
}
Related
I have JSON like this:
{
"success": 1,
"method": "getTrades",
"5183": {
"buy_amount": "0.00455636",
"buy_currency": "BTC"
},
"6962": {
"buy_amount": "52.44700000",
"buy_currency": "IOT"
},
"6963": {
"buy_amount": "383.54300000",
"buy_currency": "TNT"
},
"6964": {
"buy_amount": "3412.50000000",
"buy_currency": "FUN"
},
"6965": {
"buy_amount": "539.45000000",
"buy_currency": "XLM"
}
}
I need to convert this JSON to domain model.
public class Root {
[JsonProperty("success")]
public long Success { get; set; }
[JsonProperty("method")]
public string Method { get; set; }
public Dictionary<long, Transaction> Transactions { get; set; }
public class Transaction{
[JsonProperty("buy_amount")]
public decimal? BuyAmount { get; set; }
[JsonProperty("buy_currency")]
public string BuyCurrency { get; set; }
var model = JsonConvert.DeserializeObject<Root>(response);
I created these two models, but when I try to deserialize transactions, they are null. I got data for success and method
Either the json needs to change, or you need to modify your c# structures. Not 100% sure, but based on the JSON, the c# class should be
public class Root : Dictionary<long, Transaction> {
[JsonProperty("success")]
public long Success { get; set; }
[JsonProperty("method")]
public string Method { get; set; }
Can you change the JSON to something like this?
{
"success": 1,
"method": "getTrades",
"transaction": [
{
"id": 5183,
"buy_amount": "0.00455636",
"buy_currency": "BTC"
},
{
"id": 6962,
"buy_amount": "52.44700000",
"buy_currency": "IOT"
},
{
"id": 6963,
"buy_amount": "383.54300000",
"buy_currency": "TNT"
},
{
"id": 6964,
"buy_amount": "3412.50000000",
"buy_currency": "FUN"
},
{
"id": 6965,
"buy_amount": "539.45000000",
"buy_currency": "XLM"
}
]
}
Then you could do something like that:
public class Transaction {
public int id { get; set; }
public string buy_amount { get; set; }
public string buy_currency { get; set; }
}
public class Root {
public int success { get; set; }
public string method { get; set; }
public List<Transaction> transaction { get; set; }
}
I'm trying to fetch the data from rest api but getting null from the result.data
request4.AddHeader("Content-Type", "application/json");
request4.AddHeader("Authorization", "Bearer " + mytoken);
request4.AddParameter("application/json", "{ \"active\": true }", ParameterType.RequestBody);
var result = client4.Execute<List<RootObject>>(request4);//getting nullexcception here
//Console.WriteLine(result);
//Console.ReadKey();
foreach (var i in result.Data)
{
foreach (var j in i.sales_offices)
{
Console.WriteLine(j.state);
}
}
}
public class SalesOffice
{
public bool active { get; set; }
public string _id { get; set; }
public string name { get; set; }
public string state { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public string message { get; set; }
public List<SalesOffice> sales_offices { get; set; }
}
and from json I'm getting this result
{
"success": true,
"message": "Gtm Cities loaded successfully!",
"sales_offices": [
{
"active": true,
"_id": "XXXXX5cb57542ed50d82730d7661d",
"name": "UAXXS",
"state": "AXXX.P"
}
Please help me as it is showing no issue in the code
I have the following viewModel:
public class ProfileLocalizationViewModel
{
public ProfileViewModel Profile { get; set; }
public virtual string LanguageCode { get; set; }
public string Description { get; set; }
}
with the Profile object looking like:
public class ProfileViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsOutlet { get; set; }
public bool IsWholesaler { get; set; }
public bool IsProducer { get; set; }
public List<ProfileLocalizationViewModel> Localizations { get; set; }
}
From the client, I'm sending the following JSON:
{"Profile":{"Id":-1,"Name":"New Profiledsa","IsOutlet":false,"IsWholesaler":false,"IsProducer":false,"Localizations":null},"LanguageCode":"en","Description":"Description for selected language","__ko_mapping__":{"ignore":[],"include":["_destroy"],"copy":[],"observe":[],"mappedProperties":{"Profile.Id":true,"Profile.Name":true,"Profile.IsOutlet":true,"Profile.IsWholesaler":true,"Profile.IsProducer":true,"Profile.Localizations":true,"Profile":true,"LanguageCode":true,"Description":true},"copiedProperties":{}}}
Which gets parsed by Chrome like:
And on the server, when I try to receive a ProfileLocalizationViewModel, the values received are all null:
Any idea why this happens? Any advice greatly appreciated.
Client ajax call:
self.saveProfile = function (model, event) {
model.ItemForEditing.LanguageCode = self.SelectedLanguage.Code().toLowerCase();
var preview = ko.toJSON(model.ItemForEditing);
if (validateForm()) {
$.ajax({
type: "POST",
url: urlSaveProfile,
data: ko.toJSON(model.ItemForEditing),
contentType: 'application/json',
async: true,
beforeSend: function ()
success: function (result) {
// Handle the response here.
self.pushProfile(ko.mapping.fromJS(result.Data));
addContainer.modal('hide');
}
});
}
};
And inside preview, right before the call, there's the JSON...
I am trying to post a Json string, deserialize it, and then save it to a SQL database using MVC entity framework. Here is my model:
[Serializable]
public partial class employee
{
public int id { get; set; }
public string netid { get; set; }
public string enumber { get; set; }
public string peoplesoft { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string mi { get; set; }
public string prefix { get; set; }
public string suffix { get; set; }
public string email { get; set; }
public string tenure_year { get; set; }
public byte tenure_indicator { get; set; }
public Nullable<System.DateTime> hire_date { get; set; }
public string updated_by { get; set; }
public System.DateTime created_at { get; set; }
public System.DateTime updated_at { get; set; }
public string gender { get; set; }
public Nullable<System.DateTime> birth_date { get; set; }
}
My controller:
[HttpPost]
public ActionResult Create(ChadAPI.Models.Lookup.employee employee)
{
if (ModelState.IsValid)
{
db.employees.Add(employee);
db.SaveChanges();
return new JsonResult() { Data = employee, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
return Content("Model State Invalid");
}
And My View:
#model ChadAPI.Models.Lookup.employee
#{
ViewBag.Title = "Create";
}
<script src="~/Scripts/jquery-1.10.2.intellisense.js"></script>
<h2>Create</h2>
<input type="submit" id="Save" value="Save" />
<script>
$(function () {
$("#Save").click(function () {
alert("clicked!");
var employee = {
id: 77,
netid: 'caw63231',
enumber: '00000',
peoplesoft: '1012481',
firstname: 'Christian',
updatedby: 'caw63231',
createdat: '10/14/2013 3:02:46 PM',
updatedat: '10/14/2013 3:02:46 PM'
}
$.ajax({
type: "POST",
url: "Employees/Create",
data: employee,
success: function (data) {
console.log("success!")
},
dataType: "json",
traditional: true
});
});
});
</script>
When I press the button in the view nothing happens, and using Fiddler I can see that no JSON is passed whatsoever. What am I doing wrong?
MVC will automatically map the JSON request to your Actions parameters. The action you have written will be expecting a string object and you are trying to post it a JSON object containing an array.
You should update your action to receive an Employee object and post a JSON representation of this to the action. Like so:
$(function () {
$("#Save").click(function () {
var employee = {
id: 77,
netid : 'cfw22511',
enumber : '000000',
peoplesoft : '2322381'
//..... Add the rest of your data to the JSON object
};
$.ajax({
type: "POST",
url: "/Employees/Create",
data: employee,
success: function(data){
alert(data.Result)
},
dataType: "json",
traditional: true
});
});
});
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateChadAPI.Models.Lookup.employee employee)
{
if (ModelState.IsValid)
{
db.employees.Add(employee);
db.SaveChanges();
db.SaveChanges();
return new JsonResult() {Data = employee, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
return Content("Model State Invalid");
}
Json is an object parsed as string, when sending this object to the server, MVC automatically convert it to the object, you don't have to do this by your self, so:
public ActionResult Create(ChadAPI.Models.Lookup.employee jsonemployee)
on the other side, create the same object' in Js:
var emp=new Object()
{
id:777,
}
also, check if your javascript code is running
I am working on an ASP.NET MVC application. I have the following view model in c#:
public class ContactModel
{
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
public class PersonModel
{
public ContactModel Contact;
public PersonModel()
{
Contact = new ContactModel();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Profession { get; set; }
}
Now i have the same json model at client side which i want to post to server. I am using following jquery ajax:
$.ajax({
url: "address to controller",
type: "post",
data: JSON.stringify(data),
contentType: "application/json",
success: function () {
alert("data saved successfully");
}
});
But only PersonModel properties are get mapped but Contact properties are null. Can anybody please tell me what i am missing??
You need for format your string to proper json -
Say if you model is -
public class ContactModel
{
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
public class PersonModel
{
public ContactModel Contact { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Profession { get; set; }
}
Then you AJAX Post should be like this -
<script>
$(function () {
$('#click1').click(function (e) {
var studentData = {
"FirstName": "Rami",
"LastName": "Vemula" ,
"Contact": { "City": "Hyd"}
};
$.ajax({
url: "#Url.Action("Submit")",
type: "POST",
data: JSON.stringify(studentData),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
});
});
</script>
Then output is going to be -
Create a instance of ContactModel and assign it to contact under PersonModel after creating instance of PersonModel.
Please let me know in case of any clarification needed
If you are using #html helper for properties then form.serialize() method will bind all the properties otherwise if you are using html elements like <input> the assign their name property same as model property.
<input type="text" name="Contact.FirstName" value="#Model.Contact.FirstName"/>