Unable to deserialize a JSON string generated by a JQuery plugin - javascript

I using a JQuery plugin that enable my users to design forms. The design is saved in form of a JSON string in database. This JSON string is in following format:
{
"fields": [{
"label": "Untitled",
"field_type": "text",
"required": true,
"field_options": {
"save_to": "",
"size": "small",
"description": ""
},
"cid": "c5"
}]
}
Following is C# class structure and code that is used to deserialize this JSON string:
public class Options {
public string label {
get;
set;
}
public bool Checked {
get;
set;
}
}
public class FieldOption {
public string save_to {
get;
set;
}
public string description {
get;
set;
}
public object options {
get;
set;
}
public bool include_other_option {
get;
set;
}
public string size {
get;
set;
}
}
public class DesignField {
public string label {
get;
set;
}
public string field_type {
get;
set;
}
public bool required {
get;
set;
}
public string cid {
get;
set;
}
public List < FieldOption > field_options {
get;
set;
}
}
public class Design {
public List < DesignField > fields {
get;
set;
}
}
public partial class FormDesign: System.Web.UI.UserControl {
List < DesignField > FormFields;
public string FormDesignData {
get;
set;
}
protected void Page_Load(object sender, EventArgs e) {
Design res = JsonHelper.JsonDeserialize < Design > (FormDesignData);
}
}
JSON Helper class is given here: http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET
The problem is that it is deserializing when inner JSON objects are enclosed with [] for example:
"field_options":[{
"save_to": "",
"size": "small",
"description": ""
}]
But the plugin is not exporting the JSON in that format but in the format I mentioned before.
Please tell me how can I convert it to a valid deserializable format?

The model according to your json should be:
public class FieldOptions
{
public string save_to { get; set; }
public string size { get; set; }
public string description { get; set; }
}
public class Field
{
public string label { get; set; }
public string field_type { get; set; }
public bool required { get; set; }
public FieldOptions field_options { get; set; }
public string cid { get; set; }
}
public class RootObject
{
public List<Field> fields { get; set; }
}
I used this online tool http://json2csharp.com/ to generate it.
RootObject is the type you will use to deserialize
Using, for ex, Json.Net, your code would be
var myobj = JsonConvert.DeserializeObject<RootObject>(json);

Related

Convert array of key objects pair to a C# object

I have a api that return data in this format
{ "reult":
{ "70":
{
"type_id": 3,
"type": "forex",
"group_title": "forex",
"name": "EUR",
"title": "EUR"
},
"724":
{
"type_id": 5,
"type": "shares",
"group_title": "shares",
"name": "#ABT",
"title": "#ABT"
}
}
}
Now I want these key object pair data to a genuine C# object array. Like this
[
{
Id = 70
Type_id = 3,
Type = "forex",
Group_title = "forex",
Name = "EUR",
Title = "EUR"
},
{
Id = 724,
Type_id = 5,
Type = "shares",
Group_title = "shares",
Name = "#ABT",
Title = "#ABT"
}
]
Is it possible to do so?
[I have Updated the api returned data. Because with this format it is easy to desterilize this data with c# Dictionary]
Say you have some classes:
public class Root
{
[JsonProperty("result")]
public Dictionary<int, Data> Result {get;set;}
}
public class Data
{
[JsonIgnore]
public int Id { get; set; }
[JsonProperty("type_id")]
public int TypeId { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("group_title")]
public string GroupTitle { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
}
You can deser the original data (not the one you modified by removing "result") and then call, if you want an array out of it:
var root = JsonConvert.DeserializeObject<Root>(str);
foreach(var kvp in root.Result) kvp.Value.Id = kvp.Key;
var arr = root.Result.Values.ToArray();
ps; you need references to Newtonsoft.Json; System.Collections.Generic; System.Linq;
create class with those properties
then use below code:
JsonSerializer.Deserialize<List<object>>(jsonString);
here is link to more detail:
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0
When i deserialized your json to c# class
it is right class object
maybe your json is not correct
it is c# class:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class _70
{
public int type_id { get; set; }
public string type { get; set; }
public string group_title { get; set; }
public string name { get; set; }
public string title { get; set; }
}
public class _724
{
public int type_id { get; set; }
public string type { get; set; }
public string group_title { get; set; }
public string name { get; set; }
public string title { get; set; }
}
public class Reult
{
public _70 _70 { get; set; }
public _724 _724 { get; set; }
}
public class Root
{
public Reult reult { get; set; }
}

How to pass an array in formData

I am using formData and trying to pass an array that receives it in .Net Core backend
this is my array that i try to send truck.StateTruck:
{
0: {StaId: 6}
1: {StaId: 7}
2: {StaId: 8}
3: {StaId: 9}
}
this is my method to send my data that I try to send only the StaId and its value:
let formData = new FormData();
formData.set('DriId',truck.DriId);
formData.set('TruExdate',truck.TruExdate);
formData.set('TruAddress',truck.TruAddress);
formData.set('TruCity',truck.TruCity);
formData.set('TraId',truck.TraId);
formData.set('TruZip',truck.TruZip);
formData.set('TruYear',truck.TruYear);
formData.set('TruMake',truck.TruMake);
formData.set('TruType',truck.TruType);
formData.set('TruFuel',truck.TruFuel);
formData.set('TruAxles',truck.TruAxles);
formData.set('TruVin',truck.TruVin);
formData.set('TruDocurl',truck.TruDocurl);
formData.set('TraUnit',truck.TraUnit);
formData.set('TraMake',truck.TraMake);
formData.set('TraYear',truck.TraYear);
formData.set('TtyId',truck.TtyId);
formData.set('TraIntmaterial',truck.TraIntmaterial);
formData.set('TraEquipament',truck.TraEquipament);
formData.set('TraOption',truck.TraOption);
formData.set('Fichero',truck.Fichero);
formData.append('StateTruck',JSON.stringify(truck.StateTruck));
when printing to the console using the console.log (formData.getAll ('StateTruck')); I see
["[{"StaId":6},{"StaId":7},{"StaId":8},{"StaId":9}]"]
and my backend expects this structure:
public class TruckRequest
{
public int TruId { get; set; }
public int? DriId { get; set; }
public DateTime? TruExdate { get; set; }
public string TruAddress { get; set; }
public string TruCity { get; set; }
public int? TraId { get; set; }
public string TruZip { get; set; }
public string TruYear { get; set; }
public string TruMake { get; set; }
public string TruType { get; set; }
public string TruFuel { get; set; }
public string TruAxles { get; set; }
public string TruVin { get; set; }
public string TruDocurl { get; set; }
public string TraUnit { get; set; }
public string TraMake { get; set; }
public string TraYear { get; set; }
public int? TtyId { get; set; }
public string TraIntmaterial { get; set; }
public string TraEquipament { get; set; }
public string TraOption { get; set; }
public IFormFile Fichero { get; set; }
public string TruUregistro { get; set; }
public DateTime? TruUfecha { get; set; }
public string TruUupdate { get; set; }
public DateTime? TruUupdatefecha { get; set; }
public string TruEstado { get; set; }
public virtual ICollection<StateTruck> StateTruck { get; set; }
}
public partial class StateTruck
{
public int SruId { get; set; }
public int? StaId { get; set; }
public string SruUregistro { get; set; }
public DateTime? SruUfecha { get; set; }
public string SruUupdate { get; set; }
public DateTime? SruUupdatefecha { get; set; }
public string SruEstado { get; set; }
public int? TruId { get; set; }
}
How can I give it the correct format so that it can be received?
if you need the value converted to string, you may use
e.g.
formData.set('TruYear', truck.TruYear.toString());
for integer, e.g.
formData.set('TruYear', parseInt(truck.TruYear));
All these are passed as formData to your backend, your server should create the parser to convert to the right format, and to validate it is the right format.
Never, trust, anything submitted from frontend.
When console logging out the data you need to parse the first element in the array received from formData.getAll ('StateTruck'). The following should help in your scenario:
console.log(JSON.parse(formData.getAll("StateTruck")[0]))
According to your description, I assume you want to use FormData to pass value (include the object array) from client side to server side (Web API). If that is the case, you could refer to the following sample code:
Client side (using JQuery Ajax to call the web API method):
$(function () {
//Submit Main Form.
$("#btnCreate").click(function (event) {
//Prevent Default Region.
event.preventDefault();
//define an array to store the StateTruck
var statetruce = new Array();
for (var i = 0; i < 5; i++) {
statetruce.push({ StaId: i });
}
let formData = new FormData();
formData.set('DriId', 101);
formData.set('TruAddress', "Address 1");
formData.set('TruCity', "city A");
formData.set('TraId', 1011);
formData.set('TruZip', "zip12");
formData.set('TruYear', "years ");
formData.append('StateTruck', JSON.stringify(statetruce));
$.ajax({
url: '/api/TestAPI',
type: "post",
async: true,
data: formData,
processData: false,
contentType: false,
success: function (response) {
// window.location.href = response;
}
});
});
});
Based on the Array Object's property to create a View Model, it is used to Deserialize the array object.
Code in the Web API method:
[HttpPost]
public async Task<IActionResult> Post(IFormCollection collection)
{
var DriId = collection["DriId"].ToString();
var TruAddress = collection["TruAddress"].ToString();
var StateTruck = collection["StateTruck"].ToString();
//deserialize the object
var result = System.Text.Json.JsonSerializer.Deserialize<List<StateTruckViewModel>>(StateTruck);
//do something
return Ok("success");
}
Then debug screenshot as below:

Infragistics IgniteUI Tree Load OnDemand

I am using the plugin http://www.igniteui.com/tree/overview and want to load the tree data on demand.
My declaration of the tree is :
$("#tree").igTree({
checkboxMode: "off",
singleBranchExpand: true,
loadOnDemand: true,
dataSourceUrl : "/home/getagreements",
nodeClick: function (evt, ui) {
},
dataSourceType: "json",
initialExpandDepth: -1,
pathSeparator: ".",
bindings: {
textKey: "Text",
valueKey: "Value",
imageUrlKey: "ImageUrl",
childDataProperty: "Value",
Description: "Description"
},
},
dragAndDrop: false,
nodeExpanding: function (evt, ui) {
}
});
and the JSON output for home/getagreements is
return Json(agrmnts, JsonRequestBehavior.AllowGet);
where
List<Agreements> agrmnts = new List<Agreements>();
and the class definitions as below:
[JsonObject(MemberSerialization = Newtonsoft.Json.MemberSerialization.OptIn)]
public class AgreementNode
{
[JsonProperty(Order = 1)]
public string AgreementNbr { get; set; }
[JsonProperty(Order = 2)]
public string ExternalDescription { get; set; }
[JsonProperty(Order = 3)]
public string Description { get; set; }
[JsonProperty(Order = 4)]
public string EffDate { get; set; }
[JsonProperty(Order = 5)]
public string ExpDate { get; set; }
[JsonProperty(Order = 6)]
public string ReleaseStatus { get; set; }
[JsonProperty(Order = 7)]
public string ImageUrl { get; set; }
[JsonProperty(Order = 8)]
public string Folder { get; set; }
[JsonProperty(Order = 9)]
public string Value { get; set; }
[JsonProperty(Order = 10)]
public string Text { get; set; }
}
public class Agreements
{
public string AgreementType { get; set; }
public string Text { get; set; }
public string Value { get; set; }
public string Folder { get; set; }
public string ImageUrl { get; set; }
public List<AgreementNode> agreements { get; set; }
}
The first level data is displayed correct but when I click the node the same data is binding again. Please suggest if I am missing any configuration settings for Loading on Demand
With the current configuration the igTree is using the dataSourceUrl to request the new data from the same controller action you used to bind the initial level. At this point you would need to use the parameters the tree is providing to the controller action - path, binding and depth - to return the correct layer of data.
Here's an example of how you can do this.

Insert "Multiple Field Value" in the Same Column in MVC4?

I want to save the Multiple field Values in the same Column.
TaxField Table contain 3 Fields
1)TaxFieldID
2)DisplayName
3)PrintName
TaxFieldID = FD713788-B5AE-49FF-8B2C-F311B9CB0CC4
DisplayName = TinNo
PrintName = TinNo
The value of TinNo CinNo etc all are have default value which is saved in TaxField Table
TaxInfoTaxField Table
My View contain six fields TinNo, CstNo, PanNo, ServiceTaxNo,ExciseRegNo, CinNo.
Format to save the Value and ID in TaxInfoTaxFieldTable
TinNo = FD713788-B5AE-49FF-8B2C-F311B9CB0CC4
CstNo = 64B512E7-46AE-4989-A049-A446118099C4
CinNo =59A2449A-C5C6-45B5-AA00-F535D83AD48B
My Model
public partial class TaxInfoTaxFiled
{
public System.Guid TaxInfoTaxFieldID { get; set; }
public Nullable TaxInfoID { get; set; }
public Nullable TaxFieldID { get; set; }
public Nullable FieldTypeID { get; set; }
public string FieldValue { get; set; }
}
public partial class TaxField
{
public System.Guid TaxFieldID { get; set; }
public string DisplayName { get; set; }
public string PrintName { get; set; }
}
MyViewModel
public class TaxViewModel1
{
public System.Guid TaxInfoTaxFieldID { get; set; }
public System.Guid TaxInfoID { get; set; }
public Nullable TaxFiledID { get; set; }
public string TinNo { get; set; }
public string CstNo { get; set; }
public string ExciseRegNo { get; set; }
public string PanNo { get; set; }
public string ServiceTaxNo { get; set; }
public string CinNo { get; set; }
}
public class VisitorsEntities1 : DbContext
{
public DbSet TaxField { get; set; }
public DbSet TaxInfo { get; set; }
public DbSet TaxInfoTaxFiled { get; set; }
}
My Controller
[HttpPost]
public ActionResult Index(TaxViewModel1 TVM)
{
Type type = typeof(TaxField);
PropertyInfo[] Info = new
TaxInfoTaxField().GetType().GetProperties();
foreach (TaxInfoTaxField property in properties)
{
var Value = property.GetValue(TVM.TinNo, null);
var Value1 = property.GetValue(TVM.CstNo, null);
}
return View(Tax);
}
Sir In this below Code we pass the Properties of TaxField and it is get by TaxinfoTaxField Table
Type type = typeof(TaxField);
PropertyInfo[] Info = new TaxInfoTaxField().GetType().GetProperties();
And in 'foreach Loop ' we assigning the Value to the Variable. But how to assign the value to the Column .And How to do save the Value in FieldValue and ID in TaxFieldID of TaxInfoTaxField Table in the above format which I mentioned. Please Correct my Controller Code . I am very very new to MVC . so only I struggling for this Small Concepts. Please correct my Controller Code and help me to save the Values in the TaxInfoTaxField table. And if you have a times means please explain me the Logic used in Controller.
Thanks.

Custom POST Action including child elements

I want to replace the default Create View and Controller for my modelclass CourseEvent which should be able to handle request containing child elements. The child elements are of type public virtual ICollection<CourseEventDate>.
Model Class CourseEvent
public partial class CourseEvent
{
public CourseEvent()
{
this.CourseEventDates = new HashSet<CourseEventDate>();
this.UsersInCourseEvents = new HashSet<UsersInCourseEvent>();
}
public int CourseEventId { get; set; }
public Nullable<int> CourseFk { get; set; }
public Nullable<int> CourseEventDurationInDays { get; set; }
public Nullable<int> CourseEventDurationInHours { get; set; }
public Nullable<int> CourseEventPrice { get; set; }
public virtual Course Course { get; set; }
public virtual ICollection<CourseEventDate> CourseEventDates { get; set; }
public virtual ICollection<UsersInCourseEvent> UsersInCourseEvents { get; set; }
}
Model Class CourseEventDate
public partial class CourseEventDate
{
public int CourseEventDateId { get; set; }
public Nullable<int> CourseEventFk { get; set; }
public Nullable<System.DateTime> CourseEventDateTimeFrom { get; set; }
public Nullable<System.DateTime> CourseEventDateTimeTo { get; set; }
public virtual CourseEvent CourseEvent { get; set; }
}
If mvc would use JSON for the scafffolded POST requests, I would've considered sending a POST request using JavaScript, the JSON request would look something like this:
{
"CourseFk": "123",
"CourseEventDurationInDays": "2",
"CourseEventDurationInHours": "16",
"CourseEventPrice": "1234",
"CourseEventDate": [{
"CourseEventDateTimeFrom": "2015-05-05 08:00",
"CourseEventDateTimeTo": "2015-05-05 12:00"
},
{
"CourseEventDateTimeFrom": "2015-05-05 13:00",
"CourseEventDateTimeTo": "2015-05-05 17:00"
},
{
"CourseEventDateTimeFrom": "2015-05-06 08:00",
"CourseEventDateTimeTo": "2015-05-06 12:00"
},
{
"CourseEventDateTimeFrom": "2015-05-06 13:00",
"CourseEventDateTimeTo": "2015-05-06 17:00"
}]
}
So what's the best strategy/best practices to solve this problem?

Categories