Bassie
Bassie

Reputation: 10390

How to Embed Variable in Attribute String

In my Form.aspx page, I have the following line in Page_Load:

userName = HttpContext.Current.Request.LogonUserIdentity.Name.Split('\\')[1];

And I am using the following line to set some text on the form itself:

userLabelSecret.Text = $"Hello {userName}. Please enter a secret word or phrase:";


I would like to do something like this in the form instead:

<asp:Label ID="userLabelSecret" runat="server" Text="Hello <%=userName%>. Please enter a secret word or phrase: "></asp:Label>

However, this just shows the string <%=userName%> rather than the actual userName variable.

Is it possible to embed the variable in the Text attribute like this, instead of assigning it in Page_Load?


I tried doing this will the normal C# concatenation operator (+) but this causes the following error:

<asp:Label ID="userLabelSecret" runat="server" Text= "Hello " + <%=userName%> + ". Please enter a secret word or phrase: "></asp:Label>

The name 'userLabelSecret' does not exist in the current context

Upvotes: 0

Views: 335

Answers (3)

CodeOptimizer
CodeOptimizer

Reputation: 96

What you can do is to have one property of type string

property string username{get;set;}

property string text {get;set;}=string.Format("Hello {0}. Please enter a secret word or phrase:",username)

+ ". Please enter a secret word or phrase: ">

Upvotes: 0

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

Instead of concatenating directly by "+" operator inside asp:Label, try to use String.Concat:

<asp:Label ID="userLabelSecret" runat="server" Text= "<%= String.Concat("Hello ", userName, ". Please enter a secret word or phrase: ") %>"></asp:Label>

or plain HTML server control with similar functionality and keeping server control's name:

<label id="userLabelSecret" runat="server">Hello <%= userName %>. Please enter a secret word or phrase:</label>

CMIIW.

Upvotes: 0

Kshitij Upadhyay
Kshitij Upadhyay

Reputation: 36

No, that cannot be done. Also embedding code in mark-up is not a good practice.

Still if thats the route you want to take, the below steps will achieve the same result for you.

Make userName a public property. Then change the asp:label to just <label> and do something like:

<label>Hello <%=userName%>. Please enter a secret word or phrase:</label>

Upvotes: 1

Related Questions