6

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?

George Kagan
  • 5,913
  • 8
  • 46
  • 50

2 Answers2

5

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" });
Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183
  • when i use your code i get this : **System.Web.UI.WebControls.Literal' does not contain a definition for 'CssClass**. and in my work i must write some
  • and
    tag in some condition. how can i write those tag.
  • –  Apr 04 '11 at 09:12
  • @Raika, updated, you need to use Label instead of Literal. You need to use something like this to create a div from code behind: `var myDiv = new HtmlGenericControl("div");` – Filip Ekberg Apr 04 '11 at 09:32