0

I am new to ASP.NET and am battling to understand why I cannot get the current user name displayed in the text of a MenuItem. I created a control holding a Menu to place on all pages:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MainMenu.ascx.cs" 
Inherits="Test1.Controls.MainMenu" %>
<asp:Menu ID="NavigationMenu" CssClass="menu" runat="server"  
    EnableViewState="False" IncludeStyleBlock="False" Orientation="Horizontal" 
    MaximumDynamicDisplayLevels="4">
    <Items>
        <asp:MenuItem Text="<%=HttpContext.Current.User.Identity.Name%>" />       
    </Items>
</asp:Menu>
<div>
   User is: "<%=HttpContext.Current.User.Identity.Name%>"
</div>

The DIV at the end is to prove that <%=HttpContext.Current.User.Identity.Name%> does indeed give the current user name (it does). However, it just returns blank when used in the MenuItem Text attribute. What is the correct way to do this?


UPDATE:
I see this was downvoted without any useful comment. I have ammended this as the real question has not really been answered: how do we do this declaratively? It is hard to figure out why it works in the DIV but not four lines above in the menu. It would seem that due to the different phases the page is processed in it may be impossible to do this declaratively?

These similar posts suggests that it it impossible:
How do I make my ASP.NET server control take an embedded code block as a property value?
Why will <%= %> expressions as property values on a server-controls lead to a compile errors?

If you want to know why I want to do this it relates to another question I made:
How to specify path relative to current Master Page File

Community
  • 1
  • 1
Etherman
  • 1,777
  • 1
  • 21
  • 34

1 Answers1

0

The thing you are using does not work for the MenuItem as Steve B found out. I'm still working out why that is..

The easiest way is to do it in the code behind.

        string username = "Not Logged In";

        if (!string.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
        {
            username = HttpContext.Current.User.Identity.Name;
        }

        NavigationMenu.Items.Add(new MenuItem(username));
Dave Walker
  • 3,498
  • 1
  • 24
  • 25
  • This is the first solution that actually works, thanks. I used "NavigationMenu.Items[7].Text=HttpContext.Current.User.Identity.Name" to access an existing menu item. – Etherman Dec 01 '11 at 12:58