Dynamically add div in .aspx page

Viewed 403

I'm looking for a JavaScript-free way to dynamically add div elements inside a certain element of an aspx web page according to data passed to i.

I'm looking for something similar to razor c# where you can even create loops and write c# code that directly effects the content of the page.

It appears that razor c# doesn't work unless the page is a .cshtml page, so I'm kinda lost here since I don't want to use JavaScript.

Is there a better approach to it?

2 Answers

Say, below is the placeholder div

<div id = "maindiv">
<asp:PlaceHolder ID ="maindivs" runat="server">
</asp:PlaceHolder>
</div>

Then you may add divs to your placeholder div like below

protected void addmainDiv(int m)
{             
    for(int i = 0; i< m; i++)
    {
      System.Web.UI.HtmlControls.HtmlGenericControl newdivs = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
      newdivs.Attributes.Add("class", "maindivs");
      newdivs.ID = "createDiv";
      newdivs.InnerHtml = " I'm a div, from code behind ";
      maindivs.Controls.Add(newdivs);
   }

}

If you want to create HTML dynamically in .aspx then you can create your html code in your .cs (backend file)

string htmlAsStringToShow = "<div>" + variable + "</div>";

Then show its content in your .aspx page like this :

<%= htmlAsStringToShow %>
Related