how to generate dynamic <li> tag and hyperlink from C#

NomNomNom picture NomNomNom · Jun 4, 2013 · Viewed 8k times · Source

ok, so what i want to achieve is, generating li tag inside ul from C#, and put hyperlink button in that li tag,

i have tried this :

 ulFiles.Attributes.Add("class", "files");

                    foreach (var item in checkdocument)
                    {
                        HyperLink link = new HyperLink();
                        link.ID = "file" + item.fileid;
                        link.NavigateUrl = "~/files/attachment/result_document/" + item.resultdoc;
                        ulFiles.Controls.Add(new LiteralControl("<li>" + link + "</li>"));  
                    }    

but unfortunetly that link rendered as string, rather than a hyperlink control, any correction, how to do it correctly? thanks.

Answer

Bat_Programmer picture Bat_Programmer · Jun 4, 2013

You should use the HtmlGenericControl class to add <li> dynamically.

Try the following code and let me know if it works:

foreach (var item in checkdocument)
{
  HyperLink link = new HyperLink();
  link.ID = "file" + item.fileid;
  link.NavigateUrl = "~/files/attachment/result_document/" + item.resultdoc;
  HtmlGenericControl li = new HtmlGenericControl("li"); //Create html control <li>
  li.Controls.Add(link); //add hyperlink to <li>
  ulFiles.Controls.Add(li);  //add <li> to <ul>
}