I am sending data from database to the page with Ajax. I want to show this data with jsTree. There are as many folders as the number of data I send. but it doesn't show their names. How can I properly display data with jsTree?


My JavaScript code:
$(function () {
$.ajax({
type: "GET",
url: "/Home/anaKategori",
success: function (data) {
console.log(data);
createJSTrees(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
function createJSTrees(json) {
$('#jstree').jstree({
'core': {
'data': json
},
"plugins": ["themes", "data", "ui"]
});
}
My C# code (.net core 5.0):
public List<tumKategoriler> anaKategori()
//public string anaKategori()
//public IActionResult anaKategori()
{
foreach (var item in context.urunKategorileri.ToList())
{
if (context.urunKategorileri.Any(x=>x.urunKategorileriUstId == item.urunKategorileriId))
{
List<altKategoriler> p = new List<altKategoriler>();
foreach (var altItem in context.urunKategorileri.Where(x => x.urunKategorileriUstId == item.urunKategorileriId))
{
altKategoriler e = new altKategoriler
{
ad = altItem.urunKategorileriKategoriAdi
};
p.Add(e);
}
tumKategoriler i = new tumKategoriler
{
ustKategoriAdi = item.urunKategorileriKategoriAdi,
AltKategoriAdlari = p
};
json.Add(i);
}
else
{
tumKategoriler o = new tumKategoriler
{
ustKategoriAdi = item.urunKategorileriKategoriAdi
};
json.Add(o);
}
}
return json;
//return JsonConvert.SerializeObject(json);
//return Json(new { jsonvar = JsonConvert.SerializeObject(json) });
}
Your data structure may be wrong.You can try to return List<JsTreeModel> in anaKategori:
public class JsTreeModel
{
public string Id { get; set; }
public string Text { get; set; }
public string Parent { get; set; } = "#";
}
If it doesn't have a parent,Parent="#".If it has a parent,set parent's Id. to Parent property.
Here is sample data:
[{
id: "padre1",
parent: "#",
text: "Padre 1",
}, {
id: "padre2",
parent: "#",
text: "Padre 2"
}, {
id: "id3",
parent: "padre1",
text: "Figlio 1 di padre 1"
}, {
id: "id4",
parent: "padre1",
text: "Figlio 2 di padre 1"
}, {
id: "id5",
parent: "padre2",
text: "Figlio 1 di padre 2"
}, {
id: "id6",
parent: "id5",
text: "Figlio 1 di figlio 1 di padre 2"
}, {
id: "id7",
parent: "id5",
text: "Figlio 2 di figlio 1 di padre 2"
}, {
id: "id8",
parent: "id5",
text: "Figlio 3 di figlio 1 di padre 2"
}, {
id: "id9",
parent: "#",
text: "Figlio 3 di figlio 1 di padre 2"
}]
result:
I the url of ajax code you missed the file type. *********************************your ajax
$.ajax({
type: "GET",
url: "/Home/anaKategori",
success: function (data) {
.
.
.
*****************************try giving extention of file as here in url
$.ajax({
url : 'test.php', //like this
type : 'post',
data : {'data':'1'},
.
.
.
hope you have got the results by this fix, thank you