In my asp web application, I'm using HtmlGenericControl to populate a list.
Aspx code:
<div class="col-xs-12" id="displayDiv" runat="server">
<ul id="servicesList" runat="server"></ul>
</div>
From code Behind
private void LoadDisplayOrder()
{
Service service = new Service();
SortItem[] data = service.GetServicesDisplayOrderData();
servicesList.Controls.Clear();
for (int i = 0; i < data.Length; i++)
{
SortItem si = data[i];
using (HtmlGenericControl li = new HtmlGenericControl("li"))
{
li.Attributes.Add("class", "sortable-service-item");
using (HtmlGenericControl spanId = new HtmlGenericControl("span"))
{
using (HtmlGenericControl spanName = new HtmlGenericControl("span"))
{
using (HtmlGenericControl dragHandel = new HtmlGenericControl("span"))
{
spanId.InnerText = si.Id.ToString(CultureInfo.CurrentCulture);
dragHandel.Attributes.Add("class", "drag-handle-container");
dragHandel.InnerHtml = "<i class='fa fa-bars'></i>";
serviceIds.Add(si.Id);
spanId.Attributes.Add("style", "display: none;");
spanName.InnerText = si.Name;
li.Controls.Add(dragHandel);
li.Controls.Add(spanId);
li.Controls.Add(spanName);
servicesList.Controls.Add(li);
}
}
}
}
}
}
This populating List without any problem. now I need to generate list as same behaviour by using javascript. In above code data is a array with Id and Name. I have same JSON string look like this.
{
"Id":1,
"Name":"Doe"
},
{
"Id":2,
"Name":"Smith"
},
{
"Id":3,
"Name":"Jones"
}
I need to populate <li> by using Javascript same as what I generated <li> by using C# HtmlGenericControl. how can I do this? How to add attributes, styles, class using javascript while genearting <li>
Let's break it down into different steps:
Parsing JSON
I made a test string of your sample JSON and just called the built in javascript command to parse it and store it in an array. (Make sure your JSON is a valid JSON array - wrapped in square brackets [ ].)
Looping through JSON Array to add new li elements to ul
Reference different objects in the array by calling
array[index].Property. Add aTextNodeto set the text of theliSetting attributes - in loop
Inside your loop, you can set the
classNameand other attributes pretty easily.Hope this helps.
Whole test sample: