Install literal text with embedded code in an aspx file

In an ASP.NET project, I have a literal one. To set the text property, I used the following code:

<asp:Literal ID="ltUserName" runat="server" Text="<%= session.UserName %>" /> 

But instead of session.UserName , literal shows <%= session.UserName %> . I feel that the solution is simple, but I could not do it. How to set text using inline code?

+4
source share
5 answers

If you really want to print the session value on an HTML page, use <% = Session ["UserName"]. ToString ()%> as "<%%> will act as a server tag, and you cannot give it inside a literal control

I mean that there is no need for Literal Control, you can just use the specified encoding instead of a literal.

+5
source

Syntax = <% # ...%> - data binding syntax used to bind values ​​to manage properties when calling the DataBind method.

You need to call a DataBind - either Page.DataBind to bind all the controls on your page, or this.DataBind () to bind only a shortcut. For instance. add the following to the Page_Load event handler:

 <asp:Literal ID="ltUserName" runat="server" Text='<%# Session["UserName"]%>'></asp:Literal> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Session["UserName"] = "Sample"; this.DataBind(); } } 
+7
source

You tried:

 Text='<%= session.UserName %>' 

Single quotes may resolve it.

EDIT:

Based on this thread: stackoverflow.com/a/370263/360171

I would just replace

 <asp:Literal ID="ltUserName" runat="server" Text="<%= session.UserName %>" /> 

by

 <%= session.UserName %> 
+3
source

You cannot mix controls ( <asp:Literal /> ) with code blocks ( <%= .. %> ).

You can access the Text property from the code:

  ltUserName.Text = session.UserName; 
+1
source

Renatos's answer is correct, you must put single quotes when you are going to evaluate the expression in a property.

The same can be said with ItemTemplate , where you have controls for data binding, where you would use Text='<%=Eval("MyDataProperty")%>' .

0
source

Source: https://habr.com/ru/post/1383860/


All Articles