开发者

How to set ASP.NET label text to current user name

开发者 https://www.devze.com 2022-12-09 09:44 出处:网络
I am trying to set a user name to a label, but not sure if this is the right syntax - adding following markup generates a parse error

I am trying to set a user name to a label, but not sure if this is the right syntax -

adding following markup generates a parse error

<开发者_开发问答asp:Label ID="userNameLabel" runat="server"
     Text='<%= User.Identity.Name.Split(new char[]{'\\'})[1] %>' />

The main problem here is that, I do not know what <%= %> or <%# %> are called, thus cannot Google/Bing.

Can someone point me to a right direction?


Personally I would set the text of the label in the code behind in Page_Load

userNameLabel.Text = User.Identity.Name.Split('\\')[1];

You will need to ensure that there is a \ in the username or you will get an error.


If you're trying to convert User.Identity.Name into a couple of strings, it looks changing char[] to string[], should do the trick.


The <%# %> syntax is for data binding. It will work for what you want to do, you will need to make sure that DataBind() is called.

<asp:Label ID="userNameLabel" runat="server" Text='<%# User.Identity.Name.Split('\\')[1] %>' />

Other options include:

Set the Text property from the Page_Load event.

void Page_Load(object sender, EventArgs e)
{
    userNameLabel.Text = User.Identity.Name.Split('\\')[1];
}

Wrap the label around the write.

<asp:Label ID="userNameLabel" runat="server"><%= User.Identity.Name.Split('\\')[1] %></asp:Label>


This works as well.

    <asp:Label ID="userNameLabel" runat="server">
        <%= User.Identity.Name %>
    </asp:Label>
0

精彩评论

暂无评论...
验证码 换一张
取 消