TechQA.

        How to populate <li> using JSON

        368 views Asked by Sachith Wickramaarachchi At 2019-07-30T18:04:37+00:00 30 July 2019 at 18:04 2025-12-10T10:47:56+00:00

        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>

        javascript c# html-lists htmlgenericcontrol
        Original Q&A
        1

        There are 1 answers

        0
        dvo dvo On 2019-07-30T21:02:51+00:00 30 July 2019 at 21:02

        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 [ ].)

        var json = "[ { \"Id\":1, \"Name\":\"Doe\" }, { \"Id\":2, \"Name\":\"Smith\" }, 
                      { \"Id\":3, \"Name\":\"Jones\" } ]";
        
        var obj = JSON.parse(json);
        

        Looping through JSON Array to add new li elements to ul

        Reference different objects in the array by calling array[index].Property. Add a TextNode to set the text of the li

        var list = document.getElementById('<%= servicesList.ClientID %>');
        
        for (i = 0; i < obj.length; i++) {
            var li = document.createElement("li");
            li.appendChild(document.createTextNode(obj[i].Name));    
            list.appendChild(li);
        }
        

        Setting attributes - in loop

        Inside your loop, you can set the className and other attributes pretty easily.

        li.className = "myClass";
        li.setAttribute("data-id", obj[i].Id);
        

        Hope this helps.


        Whole test sample:

        var json = "[ { \"Id\":1, \"Name\":\"Doe\" }, { \"Id\":2, \"Name\":\"Smith\" }, 
                      { \"Id\":3, \"Name\":\"Jones\" } ]";
        
        var obj = JSON.parse(json);
        
        var list = document.getElementById('<%= servicesList.ClientID %>');
        
        for (i = 0; i < obj.length; i++) {
            var li = document.createElement("li");
            li.appendChild(document.createTextNode(obj[i].Name));
            li.className = "myClass";
            li.setAttribute("data-id", obj[i].Id);
            list.appendChild(li);
        }
        

        Related Questions in JAVASCRIPT

        • Using Puppeteer to scrape a public API only when the data changes
        • inline SVG text (js)
        • An array of images and a for loop display the buttons. How to assign each button to open its own block by name?
        • Storing the preferred font-size in localStorage
        • Simple movie API request not showing up in the console log
        • Authenticate Flask rest API
        • Deploying sveltekit app with gunjs on vercel throws cannot find module './lib/text-encoding'
        • How to request administrator rights?
        • mp4 embedded videos within github pages website not loading
        • Scrimba tutorial was working, suddenly stopped even trying the default
        • In Datatables, start value resets to 0, when column sorting
        • How do I link two models in mongoose?
        • parameter values only being sent to certain columns in google sheet?
        • Run main several times of wasm in browser
        • Variable inside a Variable, not updating

        Related Questions in C#

        • How to call a C language function from x86 assembly code?
        • What does: "char *argv[]" mean?
        • User input sanitization program, which takes a specific amount of arguments and passes the execution to a bash script
        • How to crop a BMP image in half using C
        • How can I get the difference in minutes between two dates and hours?
        • Why will this code compile although it defines two variables with the same name?
        • Compiling eBPF program in Docker fails due to missing '__u64' type
        • Why can't I use the file pointer after the first read attempt fails?
        • #include Header files in C with definition too
        • OpenCV2 on CLion
        • What is causing the store latency in this program?
        • How to refer to the filepath of test data in test sourcecode?
        • 9 Digit Addresses in Hexadecimal System in MacOS
        • My server TCP doesn't receive messages from the client in C
        • Printing the characters obtained from the array s using printf?

        Related Questions in HTML-LISTS

        • How to Bold both number and list on HTML (OL LI) without getting the sub list getting affected?
        • Border-Top on only second nav ul li
        • CSS - How to hide the 4th <li> without CSS class on WP Admin menu
        • How to adjust width of the element from angular: "p-multiselect", so that it is always as wide as the widest "li" element?
        • Need help Aligning list and image (HTML CSS)
        • Can I make list items tabable without assigning `tabindex` to each one?
        • How to Get only Change (Pts) column data (with minus values) from this Table in selenium?
        • Trying to create ol of urls
        • How to generate ul li from a nested array?
        • Creating a multilayer drop down nav bar
        • Vertically align a menu bar with text and icon elements and a cart icon outside of it
        • Ensure user selects item from filtered <UL> in an html form
        • How to select an option in a combined input and li field with Selenium?
        • Is "<li>" different from "<a>" on hover in terms of accessiblity?
        • How to Sort a List by Alphabetical order?

        Related Questions in HTMLGENERICCONTROL

        • asp.net find control inside runat div
        • How to add "li" to "ul" tag with C#
        • Combine Foreach loop and counter to add dynamically generated html to the beginning and end of every nth row
        • Dynamically generating span element inside paragraph element
        • Cannot pass value to page through HtmlGenericControl Property
        • How to populate <li> using JSON
        • HtmlGeneric Control does not contain a definition
        • unable to cast System.Web.UI.HtmlControls.HtmlInputText to System.Web.UI.HtmlControls.HtmlGenericControl
        • Pass label value to progress bar value property in Asp.net
        • Access dynamically created htmlgenericcontrols like div,label and checkbox using c#
        • Access to div from codebehind who's outside a repeater Asp.net C#
        • How to include text inside div using HttpContext?
        • Add a tag using HtmlGenericControl
        • HtmlGenericControl list keeps returning null
        • Controls.Add removing previous items from list

        Popular Questions

        • How do I undo the most recent local commits in Git?
        • How can I remove a specific item from an array in JavaScript?
        • How do I delete a Git branch locally and remotely?
        • Find all files containing a specific text (string) on Linux?
        • How do I revert a Git repository to a previous commit?
        • How do I create an HTML button that acts like a link?
        • How do I check out a remote Git branch?
        • How do I force "git pull" to overwrite local files?
        • How do I list all files of a directory?
        • How to check whether a string contains a substring in JavaScript?
        • How do I redirect to another webpage?
        • How can I iterate over rows in a Pandas DataFrame?
        • How do I convert a String to an int in Java?
        • Does Python have a string 'contains' substring method?
        • How do I check if a string contains a specific word?

        Popular Tags

        javascript python java c# php android html jquery c++ css ios sql mysql r reactjs node.js arrays c asp.net json

        Trending Questions

        • UIImageView Frame Doesn't Reflect Constraints
        • Is it possible to use adb commands to click on a view by finding its ID?
        • How to create a new web character symbol recognizable by html/javascript?
        • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
        • Heap Gives Page Fault
        • Connect ffmpeg to Visual Studio 2008
        • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
        • How to avoid default initialization of objects in std::vector?
        • second argument of the command line arguments in a format other than char** argv or char* argv[]
        • How to improve efficiency of algorithm which generates next lexicographic permutation?
        • Navigating to the another actvity app getting crash in android
        • How to read the particular message format in android and store in sqlite database?
        • Resetting inventory status after order is cancelled
        • Efficiently compute powers of X in SSE/AVX
        • Insert into an external database using ajax and php : POST 500 (Internal Server Error)
        • Privacy
        • Terms
        • Cookies
        • Homegardensmart
        • Math
        • Aftereffectstemplates