I bet this question was asked before, but I couldn't find the right keywords to search for.
I am trying to call my variable (currentUser.FirstName) in the middle of the HTML, but it won't recognize the variable if I try. It does work if I don't put HTML tags around the code.
Here's my code:
<% var currentUser = ProjectGalaxy.Website.GetCurrentUser(); %>
<% if (currentUser != null)
{ %>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/pages/Dashboard.aspx">Welcome <%=
currentUser.FirstName %></a></li>
</ul>
<% } %>
Thank you, Thomas
The variable you are creating within the first server block <%...%> is likely no longer in scope so when you exit the first server block and are writing the html you would have lost the context.
There are a couple of options depending if you are limited to addressing this in the display page only or are able to edit both the display and code behind.
Option 1. Remove the variable and refer to the underlying value from the server method directly.
There is a duplication of the call but it removes any scoping issues and keeps it localised if you are unable to edit the code behind.
<% if (ProjectGalaxy.Website.GetCurrentUser() != null) {%>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/pages/Dashboard.aspx">Welcome <%:ProjectGalaxy.Website.GetCurrentUser().FirstName%></a></li>
</ul>
<%}%>
// aspx.cs code behind
protected bool CurrentUser
{
get { return ProjectGalaxy.Website.GetCurrentUser(); }
}
// aspx display page
<% if (CurrentUser != null) {%>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/pages/Dashboard.aspx">Welcome <%:CurrentUser.FirstName%></a></li>
</ul>
<%}%>
// aspx.cs code behind
pnlWelcomeMessage.Visible = true; // during page load if condition is true
// aspx display page
<asp:Panel ID="pnlWelcomeMessage" runat="server" CssClass="nav navbar-nav navbar-right" Visible="false">
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/pages/Dashboard.aspx">Welcome <%:ProjectGalaxy.Website.GetCurrentUser().FirstName%></a></li>
</ul>
</asp:Panel>
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.