0

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

2
  • 1
    Have you already changed Label ID from userSecretLabel to userLabelSecret? Refactor both designer and code behind .cs file to match Label ID in aspx page if you don't sure. Commented Jun 17, 2016 at 8:36
  • @TetsuyaYamamoto Sorry, that was a typo! the only label I have is userLabelSecret Commented Jun 17, 2016 at 8:39

3 Answers 3

1

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

1 Comment

Thank you - if embedding code in the html is seen as bad practice I will just opt for changing it with a Label.Text="texthere";.
0

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.

Comments

0

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: ">

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.