Add li to ul from code behind in C#(Output ul li title list in loop, without controls)

Lionsure 2020-08-20 Original by the website

You need to bind the data to a title list like ul li after taking the data out of the database and displaying it on the web page in asp.net; there are generally two binding methods, one is binding with controls, and the other is loop binding with for or foreach. It is simple to bind with controls but to output extra characters on the web page. Loop binding requires a little troublesome writing binding code, but it will not output extra characters on the web page. Each has its own advantages.

After getting data from the database in .net, it is usually saved with ilist or list. These lists return less extra data and faster. You can use a for loop to bind the data to the ul li list, which is similar to the previous asp and Php. It is a concrete example.

 

Example of add li to ul from code behind in C#(Output ul li title list in loop, without controls)

The .net(C#) code is as follows:

public class Product
       {
              private int id;
              private string title;

       public int Id
              {
                     get;
                     set;
              }

       public string Title
              {
                     get;
                     set;
              }
       }

private void BindUlLi(ref IList<Product> dataListId)
       {
              string li = "<li><a href=\"{0}\">{1}</a></li>";

       string ul = null;
              for (int i = 0; i < dataListId.Count; i++)
              {
                     ul += string.Format(li, dataListId[i].Id, dataListId[i].Title);
              }
              if (ul != null)
                     ul = "<ul>" + ul + "</ul>";
       }

The database defined by each person is different, so the example does not get data from the database, but passes the got data to the binding method BindUlLi by address transfer, then which binds the data to the ul li list. The data model used in the data list simply defines the id and title fields, which can be extended according to actual needs.

It just accumulates each record in loop into the string in the example. If there are more data records, the speed will be slower. Using StringBuilder should be faster, especially when enough space is allocated to it once.