2011-12-01 61 views
0

我是ASP.NET的新手,并且正在努力理解为什么我无法获取MenuItem文本中显示的当前用户名。我创建了一个控制拿着菜单放置在所有网页:如何在MenuItem中添加用户名(声明)

<%@ 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> 

末的DIV是证明<%= HttpContext.Current.User.Identity.Name%>确实给当前的用户名(它确实)。但是,它在MenuItem Text属性中使用时仅返回空白。什么是正确的方法来做到这一点?


更新:
我看到这是downvoted没有任何有用的评论。我对此表示赞同,因为真正的问题还没有得到真正的答复:我们如何以声明的方式来做到这一点?很难弄清楚为什么它在DIV中工作,但不是菜单上方的四行。看起来,由于页面处理的阶段不同,可能无法以声明方式执行此操作?

这些类似的帖子表明它不可能:
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?

如果你想知道我为什么要做到这一点涉及到另一个问题,我提出:
How to specify path relative to current Master Page File

+0

嗡嗡...似乎MenuItem不从WebControl继承。我删除了我的答案 –

回答

0

的你正在使用的东西不适用于Steve B发现的MenuItem。我仍然在研究为什么这是..

最简单的方法是在后面的代码中执行它。

 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)); 
+0

这是第一个真正有效的解决方案,谢谢。我使用“NavigationMenu.Items [7] .Text = HttpContext.Current.User.Identity.Name”来访问现有的菜单项。 – Etherman