Come impostare il testo dell'etichetta ASP.NET sul nome utente corrente
-
05-07-2019 - |
Domanda
Sto cercando di impostare un nome utente su un'etichetta,
ma non sono sicuro se questa è la sintassi giusta -
l'aggiunta del seguente markup genera un errore di analisi
<asp:Label ID="userNameLabel" runat="server"
Text='<%= User.Identity.Name.Split(new char[]{'\\'})[1] %>' />
Il problema principale qui è che non so come si chiamano <%= %>
o <%# %>
, quindi non posso Google / Bing.
Qualcuno può indicarmi la giusta direzione?
Soluzione
Personalmente imposterei il testo dell'etichetta nel codice dietro in Page_Load
userNameLabel.Text = User.Identity.Name.Split('\\')[1];
Dovrai assicurarti che ci sia un \ nel nome utente o otterrai un errore.
Altri suggerimenti
Se stai cercando di convertire User.Identity.Name in un paio di stringhe, sembra che la modifica di char [] in string [], dovrebbe fare il trucco.
<% #% > la sintassi è per l'associazione dei dati. Funzionerà per quello che vuoi fare, dovrai assicurarti che DataBind () sia chiamato.
<asp:Label ID="userNameLabel" runat="server" Text='<%# User.Identity.Name.Split('\\')[1] %>' />
Altre opzioni includono:
Imposta la proprietà Text dall'evento Page_Load.
void Page_Load(object sender, EventArgs e)
{
userNameLabel.Text = User.Identity.Name.Split('\\')[1];
}
Avvolgi l'etichetta attorno alla scrittura.
<asp:Label ID="userNameLabel" runat="server"><%= User.Identity.Name.Split('\\')[1] %></asp:Label>
Anche questo funziona.
<asp:Label ID="userNameLabel" runat="server">
<%= User.Identity.Name %>
</asp:Label>