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?

2 Answers 2

6

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" });
Sign up to request clarification or add additional context in comments.

2 Comments

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 <li> and <div> tag in some condition. how can i write those tag.
@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");
2

You can try and use HtmlGenericControl. You can define the tag name of a html element. Find more about it here: http://msdn.microsoft.com/en-us/library/7512d0d0(v=vs.71).aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.