In an ASP.NET project, I have a literal. In order to set the text property, I used the following code:
<asp:Literal ID="ltUserName" runat="server" Text="<%= session.UserName %>" />
But instead of value of session.UserName
, literal shows <%= session.UserName %>
. I feel that solution is simple but I couldn't do it. How can set the text with inline code?
The syntax =<%# ... %> is Data binding syntax used to bind values to control properties when the DataBind method is called.
You need to call DataBind - either Page.DataBind to bind all the controls on your page, or this.DataBind() to bind just the label. E.g. add the following to your 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();
}
}
If you actually want to print the session value in the HTML page just use <% =Session["UserName"].ToString()%> as "<% %> will act as server tag and you cant give it inside the literal control
I mean no need of Literal Control can just use mentioned coding instead of literal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With