Infragistics IgniteUI Tree Load OnDemand - javascript

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.

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:

How can I fill array with model properties in controller action and pass to view?

I have a model with a table namely Resource that consist of multiple properties. I want define an array and fill that with Id,Latitude and Longitude properties in action namely DistanceMCalculate() in controller and pass this array to javascript in view in my MVC project.
This is my model in edmx:
public partial class Resource
{
public int Id { get; set; }
public int Code { get; set; }
public string Name { get; set; }
public Nullable<System.DateTime> StartHour { get; set; }
public string Address { get; set; }
public Nullable<System.DateTime> Arrivetime { get; set; }
public Nullable<int> ArriveTimeDuration { get; set; }
public Nullable<int> ProgressPercent { get; set; }
public Nullable<int> ResourceTypeId { get; set; }
public Nullable<decimal> Latitude { get; set; }
public Nullable<decimal> Longitude { get; set; }
public virtual ResourceType ResourceType { get; set; }
}
}
And this is my action and I want add Id,Latitude and Longitude properties of model to an array(arraylist) and pass to view in javascript. I need just array in view.how can I do it?
public ActionResult DistanceMCalculate()
{
var model= db.Resource.Where(p => p.ResourceTypeId == 1 && p.Latitude != null).ToList();
return Json();
}
Thanks a lot
Try this:
public decimal?[][] DistanceMCalculate()
{
var result= db.Resource
.Where(p => p.ResourceTypeId == 1 && p.Latitude != null)
.Select(x => new decimal?[] { x.Id, x.Latitude, x.Longitude })
.ToArray();
return result;
}

Reading Javascript FormData value in Asp.net Web api Httpresponsemessage

I have a Web api which is decorated with [HttpPost] which is used to upload all information passed in parameter but getting this error
Error
Controller
[HttpPost]
public HttpResponseMessage questionnairesubmit(HttpRequestMessage form)
{
//want to get json of "questionlist" which is send from javascript like
var QuestionnaireList = JsonConvert.DeserializeObject<List<outRightLogos.Areas.client.WebApiModel.AttributeValueTB>>(form["questionlist"]);
}
Here is javascript sending Json model with name questionlist this I want to fetch in controller.I read FormData() from Here
Javascript
var data = new FormData();
var QuestionnaireList = [];
QuestionnaireList.push({
FieldID: $(this).attr("data-fieldid"),
attributeID: $(this).attr("data-attributeid"),
attributeValue: $(this).val(),
websitesID: 2,
OrderID: $('#orderid').val(),
orderbitID: $('#orderbidid').val(),
serviceId: $(this).attr("data-serviceid"),
subServiceId: $(this).attr("data-subserviceid"),
IsSubmit: IsSubmit,
});
data.append("questionlist", JSON.stringify(QuestionnaireList));
$.ajax({
type: "POST",
url: path,
contentType: 'application/json',//"application/json; charset=utf-8",
processData: false,
dataType: "json",
data: data,
success: function (result) {
if (result.sucess == "save") {
alert('Your form has been saved.');
}
else if (result.sucess == "Submit") {
alert('Your form has been submitted.');
window.location.href = result.Url;
}
},
error: function (result) {
alert('Oh no ');
}
});
Here is a model class AttributeValueTB
Class
public class AttributeValueTB
{
public long attributeValueID { get; set; }
[Required]
[StringLength(200)]
public string attributeValueCode { get; set; }
public int FieldID { get; set; }
public int attributeID { get; set; }
public string attributeValue { get; set; }
public int websitesID { get; set; }
public long OrderID { get; set; }
public long orderbitID { get; set; }
public long serviceId { get; set; }
public long subServiceId { get; set; }
public string extra1 { get; set; }
public string extra2 { get; set; }
[StringLength(200)]
public string attributeCode { get; set; }
public bool isActive { get; set; }
public bool isShow { get; set; }
public bool IsSubmit { get; set; }
[Column(TypeName = "date")]
public DateTime? createDate { get; set; }
[Column(TypeName = "date")]
public DateTime? modifiedDate { get; set; }
public int? createBy { get; set; }
public int? modifiedBy { get; set; }
[Column(TypeName = "timestamp")]
[MaxLength(8)]
[Timestamp]
public byte[] Timestamp { get; set; }
}
You don't need to serialize anything manually, as long as you've provided a model class in C#.
Json.NET is quite smart and serializes your parameters automagically.
[HttpPost]
public HttpResponseMessage QuestionnaireSubmit(AttributeValueTB form)
{
// Form is serialized and can be used here
}
If you'd like to read the cookies too, you could use Request.Cookies in this method.
you need to collect information from 'jsoncontent' not from 'form'
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
and if you using class object as parameter also work with your context, need to change the method as put like this.
[HttpPut]
public HttpResponseMessage Put(int id)
{
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
...
}

Unable to deserialize a JSON string generated by a JQuery plugin

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

Categories