Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding variable in HTML from another c# class

I am using an ASP.NET framework. Within my welcome page (after a user logs in) I want to customize the paragraph text to include their login information. For example:

<p>
   Welcome to the website!
</p>

Is what the code would have currently, but what I want is:

<p>
       Welcome <var=Username> to the website!
</p>

Now obviously that is not correct, i didn't expect it to be. I just want to demonstrate what i am trying to do. I thought about using JavaScript to accomplish this somehow, but that seemed a bit overly complicated. My variable "Username" comes from another class in a .cs file elsewhere. How can I embed that variable into my <p></p> ?

like image 315
Nibirue Avatar asked Apr 26 '26 22:04

Nibirue


2 Answers

Add a label in your markup:

<p>
       Welcome <asp:Label ID="lblUsername" runat="server" /> to the website!
</p>

And then in the code behind:

protected void Page_Load(object sender, EventArgs e)
{
    lblUsername.Text = "username";  // set to the username variable here
}
like image 107
Slippery Pete Avatar answered Apr 28 '26 12:04

Slippery Pete


You could use an <asp:Literal in place of your marker then in the Page_Load set the value as required ltUsername.Text = UserName;

<p>Welcome <asp:Literal ID="ltUsername" runat="server" /> to the website</p>

and in your code behind

protected void Page_Load(object sender, EventArgs e)
{
    ltUsername.Text = Username; // whatever that may be
}

The literal outputs only what you supply - whereas an asp:Label will wrap your text in a <span> tag and adds extra mark-up which can be confusing. For that reason I only use asp:Label for actual <label> elements (those associated with an input).

like image 29
Simon Martin Avatar answered Apr 28 '26 11:04

Simon Martin