Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set literal text with inline code in aspx file

Tags:

c#

asp.net

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?

like image 473
sevenkul Avatar asked Dec 04 '22 19:12

sevenkul


2 Answers

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(); 
    }

}
like image 164
Prince Antony G Avatar answered Dec 24 '22 08:12

Prince Antony G


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.

like image 23
Thomas Siranjeevi Avatar answered Dec 24 '22 08:12

Thomas Siranjeevi