I feel somewhat foolish asking such a simple question, but I can’t seem to find an answer. I’m new to ASP.NET (C#), but I’m learning by building a simple set of web pages that display a report. I have a variable that represents a company name. I need to output this variable in multiple places on the web page. The only way I have found to output a variable this is with:
company_name.Text = "Acme Windows";
then
<asp:literal id="company_name" runat="server" />
My problem is that I want to use company_name in multiple places on the page. Do I really have to create a separate variable holding the the same value for each time it is placed on the page? If I just copy the above XML code to all the places I want to show the variable it obviously creates a compile error since that ID is already defined.
I feel like I’m missing something very obvious.
The easiest way to do this is to create a string variable or property in your code-behind class and use the
<%= %>notation (short forResponse.Write) to render it on your page inline:.NET 4.0 introduces a new shortcut notation (Html Encoding Blocks) to html-encode your output:
Regarding your original approach, ASP.NET web controls like
Literalrepresent individual parts of a web page – you can’t use them multiple times on a page because the object instancecompany_namerefers to the specific part of the HTML generated by the<asp:literal>in your .aspx page.