How can I convert string to JSON in Model class - javascript

I would like convert string to JSON while receiving the value from API. I am sending value from postman but I am unable to convert it to the JSON object in the model class ,I have decorated model class with the custom decorator. Thanks in Advance.
This is the Model Class and I wrote custom JSON convertor.
namespace WebApplication2.Models
{
[Serializable]
public class Test
{
[JsonConverter(typeof(UserConverter))]
public AS_AscContext AscParcelContext { get; set; }
}
public class AS_AscContext
{
public string ShellType { get; set; }
public string LayoutName { get; set; }
}
public class UserConverter : JsonConverter
{
private readonly Type[] _types;
public UserConverter(params Type[] types)
{
_types = types;
}
public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
}
else
{
JObject o = (JObject)t;
IList<string> propertyNames = o.Properties().Select(p => p.Name).ToList();
o.AddFirst(new JProperty("Keys", new JArray(propertyNames)));
o.WriteTo(writer);
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return _types.Any(t => t == objectType);
}
}
This is the controller receiving value
[HttpPost]
public IActionResult Privacy([FromBody]Test aS_AggregatorRequest)
{
return View();
}
This is the postman collection

Try to change your postman JSON like this,
{
"ascParcelContext": {
"shellType": "ceme-sales-wallaby",
"layoutName": "value"
}
}
Don't escape any of the JSON data.

your json has another json inside. So it is better to fix the api but if you don't have an access try this
[HttpPost]
public IActionResult Privacy([FromBody]JObject jsonObject)
{
jsonObject["ascParcelContext"]= JObject.Parse( (string) jsonObject["ascParcelContext"]);
Test test = jsonObject.ToObject<Test>();
.....
}
public class Test
{
[JsonProperty("ascParcelContext")]
public AS_AscContext AscParcelContext { get; set; }
}
public class AS_AscContext
{
[JsonProperty("shellType")]
public string ShellType { get; set; }
[JsonProperty("layoutName")]
public string LayoutName { get; set; }
}

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

mvc controller is passing in null from javascript object that has data

I have an MVC controller that somehow is passing in Null to it
Controller:
[HttpPost]
public ActionResult UpdateAllNodes(IEnumerable<ReportGroup> reportGroups)
{
// this is custom return..
return JsonCamel(null);
}
PROBLEM : reportGroups is null
javascript ajax post
$.post(updateAllNodeUri, JSON.stringify({ reportGroups: homogeneous.data() }));
Chrome Dev Tools Form Data:
{"reportGroups":[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1,"items":[],"index":0},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2,"items":[],"index":1},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3,"items":[],"index":2},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5,"items":[],"index":3},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4,"items":[],"index":4},
{"ReportGroupName":"Node","index":5}
]}:
So I have the reportGroups in controller along with the JSON as reportGroups: thus I'm lost on why it is null.
Also here here the poco class for the ReportGroup
public class ReportGroup : BaseEntity
{
public override int Id { get; set; }
public string ReportGroupName { get; set; }
public int? ReportGroupNameResID { get; set; }
public int SortOrder { get; set; }
}
Kendo data calls , then I can output to console and see the data as well
console.log(homogeneous.data());
// ### Send the Data to the server
var updateAllNodeUri = "/Report/UpdateAllNodes";
Based on the JSON data you get from Chrome Dev Tools, you are actually sending the JSON with this model:
JSON:
{"reportGroups":[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1,"items":[],"index":0},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2,"items":[],"index":1},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3,"items":[],"index":2},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5,"items":[],"index":3},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4,"items":[],"index":4},
{"ReportGroupName":"Node","index":5}
]}:
Model:
public class ReportGroup
{
public int Id { get; set; }
public string ReportGroupName { get; set; }
public object ReportGroupNameResID { get; set; }
public int SortOrder { get; set; }
public List<object> items { get; set; }
public int index { get; set; }
}
public class RootObject
{
public List<ReportGroup> reportGroups { get; set; }
}
The RootObject class is the one being received by your controller which is not the expected parameter.
Try transforming the JSON to this format:
[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1,"items":[],"index":0},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2,"items":[],"index":1},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3,"items":[],"index":2},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5,"items":[],"index":3},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4,"items":[],"index":4},
{"ReportGroupName":"Node","index":5}
]
Javascript:
$.post(updateAllNodeUri, JSON.stringify(homogeneous.data()));

Why are some of my values not getting populated by webapi

I'm working on a web-api controller. I built a DTO to hold a Note.
public class NoteContainer
{
public long? NoteId { get; set; }
public string Type { get; set; }
public string NoteText { get; set; }
public NoteContainer(Note note, string type = null)
{
NoteId = note.Id;
NoteText = note.NoteText;
Type = type;
}
}
I have a method in my controller:
[HttpPost]
public void EditNote(NoteContainer container)
{
//do work here
}
Before the NoteContainer is sent from the client it has all values. When it gets to the server, type is null! Should I not use a variable named type? Why am I losing the value?
Using Postman I'm sending this json:
{
"noteId": 10,
"type": "person",
"noteText": "loves broccoli",
}
That needs default constructor I believe. The problem can be that the Note class gets instantiated first and is given to NoteContainer.

Convert to List<T> or T[] from Json array in C#

I have a json data:
"{\"list\":[{\"PlId\":1,\"PstId\":1,\"MonthlyValue\":\"00,00\"},{\"PlId\":2,\"PstId\":1,\"MonthlyValue\":\"00,00\"},{\"PlId\":3,\"PstId\":1,\"MonthlyValue\":\"00,00\"},{\"PlId\":4,\"PstId\":1,\"MonthlyValue\":\"00,00\"},{\"PlId\":5,\"PstId\":1,\"MonthlyValue\":\"00,00\"}]}"
I want to the json data convert to List but JsonConvert.Deserialize(jsonData) return null.
[Serializable]
public class DecryptedMonthlyPremiumScale
{
[DataMember]
public int PlId { get; set; }
[DataMember]
public int PstId { get; set; }
[DataMember]
public string MonthlyValue { get; set; }
}
I tried this method: How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?
What is wrong?
Thanks.
You need to create a wrapper class to deserialize properly:
[Serializable]
public class DecryptedMonthlyPremiumScale
{
[DataMember]
public int PlId { get; set; }
[DataMember]
public int PstId { get; set; }
[DataMember]
public string MonthlyValue { get; set; }
}
public class Root
{
public IList<DecryptedMonthlyPremiumScale> list {get;set;}
}
var obj = JsonConvert<Root>(json);
Another approach is to use JObject to get the root element and then deserialize:
var parsed = JObject.Parse(json)["list"].ToObject<IList<DecryptedMonthlyPremiumScale>>();

Categories