Raika Raika - 1 month ago 6
ASP.NET (C#) Question

Write Html Markup from code behind in asp.net


If The title is confusing suggest to change it


What is the Best way to write my own HTML from code behind?

I currently use this:

<asp:Literal ID="ltr" runat="server"></asp:Literal>


and from code behind:

ltr.Text = "<p class=\"specific-class\"></p>";


Is it a right to do something like this?

Is there a better way to do this?

Answer

You can do it like that, but please don't. For the sake of your fellow developers in the past, present and the future, seperate your code from your design. Now, if you must write markup in code behind, that is most certainly a way to do it.

However, if all you want is to add a literal / span / textbox with a certain class you can do something like this instead:

( Given that you have a panel with runat="server" that is named "myPanel" )

myPanel.Controls.Add(new Label
                     { Text = "Hello!", CssClass = "specific-class" });