How to add a`ul` to a`li` HTML element via c#code?

Asked

Viewed 700 times

3

I’m going to have a list of multiple clients, and I wanted to add these clients to one ul of the element li in HTML, you can add these clients dynamically (because each search performed on the system can bring a number of clients) via code c# ?

  • Yes, your project is MVC or Webforms?

  • He is in Webforms

  • Are you using Razor or aspx?

  • I’m not wearing no

  • Sorry guy, yesterday I was already leaving the company, I’ll try to do today, so I try I put here whether I got it or not, thank you !

  • I made it, thank you very much!

Show 1 more comment

2 answers

5


You can do it this way (inside your file .aspx):

<ul>
    <% var numeros = new List<int>{1, 2, 3};
       foreach (int i in lista)
        {
            %> <li> <%: i %> </li>
     <% } %>
</ul>

In this example, I am creating a list with three numbers and printing each one of them in the tag <li>.

The only thing you need to adapt is to put your list on foreach.

1

Follow another example that can be done by .aspx.Cs(Codebehind)

using System.IO;   

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<Cliente> lstCliente = new List<Cliente>
        {
            new Cliente{ Id = 1, Nome = "Cliente1"},
            new Cliente{ Id = 2, Nome = "Cliente2"},
            new Cliente{ Id = 3, Nome = "Cliente3"},
            new Cliente{ Id = 4, Nome = "Cliente4"},
        };

        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

        htmlWriter.RenderBeginTag(HtmlTextWriterTag.Ul); //Cria a tag ul

        foreach (Cliente cliente in lstCliente)
        {
            htmlWriter.RenderBeginTag(HtmlTextWriterTag.Li); //Cria tag li
            htmlWriter.Write(string.Concat(cliente.Id, ": ", cliente.Nome));
            htmlWriter.RenderEndTag(); //Fecha tag li
        }                       

        htmlWriter.RenderEndTag(); Fecha tag ul

        ltListaClientes.Text = stringWriter.ToString();
    }
}

In the .aspx I added a literal to receive the list

<asp:Literal id="ltListaClientes" runat="server" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.