Syncfusion TreeView doesnt show data - asp.net

I have a list that matches the requirements that I get through the request from js.
Data from the request comes filled in, but the list is not displayed
< ejs-treeview id="treedata" created="created">
< e-treeview-fields dataSource="#Model.Items" id="LevelCode" parentId="ParentLevelCode" text="Name" hasChildren="HasChild"></e-treeview-fields>
< /ejs-treeview>
function created()
{
getCategories();
}
function getCategories() {
let treedata = document.getElementById('treedata').ej2_instances[0];
let request = new ej.base.Ajax(`/Category/GetAll`, 'GET');
request.send();
request.onSuccess = data => {
if (treedata.element !== undefined) {
let final = JSON.parse(data);
treedata.fields.dataSource = final.Categories;
treedata.dataBind();
treedata.refresh();
}
};
}
public class GetAllCategoriesHandlerResponseItem
{
public string Id { get; set; }
public string Name { get; set; }
public bool HasChild { get; set; }
public string LevelCode { get; set; }
public string ParentLevelCode { get; set; }
}

In TreeView component, the fields property has been provided to set or get the data source and other data-related information. You can use this property to dynamically change the TreeView component data source. But you need to specify the properties in its predefined structure to update the TreeView data source.
Check the below code snippet.
function getCategories() {
let treedata = document.getElementById('treedata').ej2_instances[0];
let request = new ej.base.Ajax(`/Category/GetAll`, 'GET');
request.send();
request.onSuccess = data => {
if (treedata.element !== undefined) {
let final = JSON.parse(data);
treedata.fields = {datasource: final.Categories, id:"LevelCode", parentId:"ParentLevelCode", text:"Name", hasChildren:"HasChild" };
treedata.dataBind();
treedata.refresh();
}
};
}
You can refer to the below link to know about the details.
https://www.syncfusion.com/kb/10135/how-to-refresh-the-data-in-ej2-treeview

Related

Consuming web api with RestSharp basic authentication return null

I am trying to consume an endpoint with RestSharp with Basic authentication.
I followed the instructions on the documentation https://restsharp.dev/getting-started/getting-started.html
The request was successful but I think the request body was malformed.
How can I get this to work
internal BalanceInquiryResponse BalanceInquiryRest(BalanceInquiryRequest BalanceInquiryRequest, Settings Settings)
{
// BalanceInquiryResponse BalanceInquiryResponse = new BalanceInquiryResponse();
var client = new RestClient(Settings.BaseUrl + "All/Inquiry");
client.Authenticator = new HttpBasicAuthenticator(Settings.Username, Settings.Password);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(new
{
Acc = BalanceInquiryRequest.Acc
});
IRestResponse response = client.Execute(request);
IRestResponse<BalanceInquiryResponse> res = client.Execute<BalanceInquiryResponse>(request);
if (response.IsSuccessful)
{
BalanceInquiryResponse = new BalanceInquiryResponse
{
responseInquiry = res.Data.responseInquiry,
ResponseDescription = res.Data.ResponseDescription,
ResponseMessage = res.Data.ResponseMessage
};
return BalanceInquiryResponse;
}
else
{
BalanceInquiryResponse = new BalanceInquiryResponse
{
ResponseDescription = responseses.ErrorMessage,
};
return BalanceInquiryResponse;
}
}
This is my response body
{
"responseMessage": "Successful",
"responseDescription": "Request Successful",
"responseInquiry": null
}
When I tried with postman I got
{
"ResponseMessage": "Successful",
"ResponseDescription": "Request Successful",
"response": {
"AvalBal": 586324.42,
"ReverAmt": 0,
"AccCurrency": "US "
}
}
IRestResponse<BalanceInquiryResponse> res = client.Execute<BalanceInquiryResponse>(request);
So there is a specific reason...you are putting BalanceInquiryResponse in the generic IRestResponse above.
With the above call, this should automatically hydrate the BalanceInquiryResponse object, and you shouldn't need to hand map.
Aka, you should ~not~ need this below code:
BalanceInquiryResponse = new BalanceInquiryResponse
{
responseInquiry = res.Data.responseInquiry,
ResponseDescription = res.Data.ResponseDescription,
ResponseMessage = res.Data.ResponseMessage
};
I think your issue is that your POCO object (BalanceInquiryResponse) should perfectly match the "structure" of the JSON.
Change your BalanceInquiryResponse to PERFECTLY match the json "properties".
and recognize you have a nested object.
I think it it would be:
public class ResponsePoco {
public double AvalBal { get; set; }
public int ReverAmt { get; set; }
public string AccCurrency { get; set; }
}
public class BalanceInquiryResponse{
public string ResponseMessage { get; set; }
public string ResponseDescription { get; set; }
public ResponsePoco response { get; set; }
}
Pay attention the to "ResponsePoco response"..note the variable name is LOWERCASE .. because...the json has a lowercase "response" in it.
I have called the (child) object "ResponsePoco" to highlight the difference between the object name and the variable name.
If you cannot "perfectly" match the Poco properties. you can use attributes to "massage" the discrepencies. As seen here:
https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm
public class Videogame
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("release_date")]
public DateTime ReleaseDate { get; set; }
}

asp.net put an empty C# list to razor view and fill it up inside

I want to put an empty C# List to the razor view. Inside of the view I get array of data (taken from JavaScript code). Fill the content of the array into the C# List and put it back to the controller.
Now, I know that is not possible, then I find a more simpler solution, see details in my example.
One Item of the collection
public class GrafikSpielItem
{
public String Stil { get; set; }
public int XStart { get; set; }
public int YStart { get; set; }
public int XStop { get; set; }
public int YStop { get; set; }
public String Farbe { get; set; }
}
controller class
// GET: GrafikSpiel
[HttpGet]
public ActionResult AufgabeB(string[] arr)
{
// arr is the JSON-String from Grafik.js
if (arr == null) return View();
List<GrafikSpielItem> items = new List<GrafikSpielItem>();
// adapted from: https://stackoverflow.com/questions/19910476/c-sharp-parsing-json-array-of-objects
// Thanks to: Bibaswann Bandyopadhyay
JArray array = JArray.Parse(arr[0]);
foreach (JObject obj in array.Children<JObject>())
{
var item = new GrafikSpielItem();
int nCounter = 1;
foreach (JProperty singleProp in obj.Properties())
{
switch(nCounter)
{
case 1: item.Stil = singleProp.Value.ToString(); break;
// case 2: ..
default:
break;
}
nCounter++;
}
items.Add(item);
}
// not implemented yet
// connect to database
// db.SetData(items)
return RedirectToAction("Index");
}
Razor view
...
// moved source code from here to JS
<script src="~/Scripts/Grafik.js"></script>
</body>
</html>
JavaScript: Grafik.js
// convert simple array to JSON and send it back to controller
var arrStr = encodeURIComponent(JSON.stringify(linesArray));
var url = "AufgabeB?arr=" + arrStr;
window.location.href = url;
I found a solution - see edited code - thanks to user mortb and user Bibaswann Bandyopadhyay.

A circular reference was detected while serializing entities with one to many relationship

How to solve one to many relational issue in asp.net?
I have Topic which contain many playlists.
My code:
public class Topic
{
public int Id { get; set; }
public String Name { get; set; }
public String Image { get; set; }
---> public virtual List<Playlist> Playlist { get; set; }
}
and
public class Playlist
{
public int Id { get; set; }
public String Title { get; set; }
public int TopicId { get; set; }
---> public virtual Topic Topic { get; set; }
}
My controller function
[Route("data/binding/search")]
public JsonResult Search()
{
var search = Request["term"];
var result= from m in _context.Topics where m.Name.Contains(search) select m;
return Json(result, JsonRequestBehavior.AllowGet);
}
When I debug my code I will see an infinite data because Topics will call playlist then playlist will call Topics , again the last called Topic will recall playlist and etc ... !
In general when I just use this relation to print my data in view I got no error and ASP.NET MVC 5 handle the problem .
The problem happens when I tried to print the data as Json I got
Is there any way to prevent an infinite data loop in JSON? I only need the first time of data without call of reference again and again
You are getting the error because your entity classes has circular property references.
To resolve the issue, you should do a projection in your LINQ query to get only the data needed (Topic entity data).
Here is how you project it to an anonymous object with Id, Name and Image properties.
public JsonResult Search(string term)
{
var result = _context.Topics
.Where(a => a.Name.Contains(term))
.Select(x => new
{
Id = x.Id,
Name = x.Name,
Image = x.Image
});
return Json(result, JsonRequestBehavior.AllowGet);
}
If you have a view model to represent the Topic entity data, you can use that in the projection part instead of the anonymous object
public class TopicVm
{
public int Id { set;get;}
public string Name { set;get;}
public string Image { set;get;}
}
public JsonResult Search(string term)
{
var result = _context.Topics
.Where(a => a.Name.Contains(term))
.Select(x => new TopicVm
{
Id = x.Id,
Name = x.Name,
Image = x.Image
});
return Json(result, JsonRequestBehavior.AllowGet);
}
If you want to include the Playlist property data as well, you can do that in your projection part.
public JsonResult Search(string term)
{
var result = _context.Topics
.Where(a => a.Name.Contains(term))
.Select(x => new
{
Id = x.Id,
Name = x.Name,
Image = x.Image,
Playlist = x.Playlist
.Select(p=>new
{
Id = p.Id,
Title = p.Title
})
});
return Json(result, JsonRequestBehavior.AllowGet);
}

Asp.Net Core: How to json serialize and deserialize IFormCollection?

In a controller I serialized form data to json and saved to database:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(IFormCollection formData)
{
var json = JsonConvert.SerializeObject(formData);
var doc = new Doc()
{
Subject = formData["subject"],
Content = json
};
_context.Docs.Add(doc);
_context.SaveChanges();
return RedirectToAction("Edit", new { Id = doc.Id });
}
Now, I'd like to deserialize form data and reconstruct the form:
public IActionResult Edit(int id)
{
var doc = _context.Docs
.Where(o => o.Id == id).FirstOrDefault();
if (doc == null)
{
ViewData["ErrorMessage"] = "Not found";
return View("Error");
}
var formData = JsonConvert.DeserializeObject<IFormCollection>(doc.Content);
ViewData["FormData"] = formData;
return View(doc);
}
The above will throw an exception at deserialization:
JsonSerializationException: Cannot create and populate list type Microsoft.AspNetCore.Http.IFormCollection. Path '', line 1, position 1.
If I do not specify type, then deserialization succeeds; but I prefer it
to be deserialized to IFormCollection. What is the proper way to deserialize IFormCollection?
Also, the reason I'm saving json is because, I'm dealing with 30 or so types of forms, and I do not want to create strongly typed model objects for each of them. Any advice is welcome.
The way I used to deal with json object in Database:
In your entity object add an other class to handle mapping with your json object :
public class Contact
{
public int Id { get; set; }
internal string _Data { get; set; }
[NotMapped]
public UserData Data
{
get { return _Data == null ? null : JsonConvert.DeserializeObject<UserData>(_Data); }
set { _Data = JsonConvert.SerializeObject(value); }
}
}
public class UserData
{
public string Name { get; set; }
//Add your json data here
}
And my controller look like
public IActionResult Add(AddContactViewModel model)
{
var contact = new Contact()
{
Data = JsonConvert.DeserializeObject<UserData>(model.Data.ToString())
};
_contactService.Add(contact);
return new OkObjectResult(contact);
}
public class AddContactViewModel
{
public JObject Data { get; set; }
}
Thank's to mapping, when you access the object data contained by the object contact you can access all your data préviously defined in the UserData object (Object names can change in your case)
var contact = new Contact()
{
Data = JsonConvert.DeserializeObject<UserData>(model.Data.ToString())
};
contact.Data.Name;

How to post JSON data to SQL using ajax post & knockout

I have a pretty straightforward view model:
var ProjectViewModel = {
ProjectName: ko.observable().extend({ required: "" }),
ProjectDescription: ko.observable().extend({ required: "" }),
ProjectStartDate: ko.observable(),
ProjectEndDate: ko.observable()
};
I want to save this data that is located in my viewmodel to my SQL server.
I have a class defining this View Model in my Server Side Code:
public class Projects
{
public string ProjectName { get; set; }
public DateTime ProjectStartDate { get; set; }
public DateTime ProjectEndDate { get; set; }
public string ProjectDescription { get; set; }
}
I also have this web method to receive the code:
[WebMethod]
public bool SaveProject(string[] JSONDATA)
{
TaskNinjaEntities entities = new TaskNinjaEntities();
foreach (var item in JSONDATA)
{
Console.WriteLine("{0}", item);
}
return true;
}
And finally I have this POST that does not want to send the data to the server:
function SaveMe() {
var data = ko.toJSON(ProjectViewModel);
$.post("CreateProject.aspx/SaveProject", data, function (returnedData) {
});
}
I get nothing from the returned data in this post method, also added breakpoint in server side code, and it doesn't hit it at all. My URL is correct and the Viewmodel converts to JSON without hassle.
Make the web method static.
[WebMethod]
public static bool SaveProject(string[] JSONDATA)
{
TaskNinjaEntities entities = new TaskNinjaEntities();
foreach (var item in JSONDATA)
{
Console.WriteLine("{0}", item);
}
return true;
}

Resources