0

我有一个标签,我想将此标签的文本设置为

HTTPContext.Current.User.Identity.Name

所以我写了

Text = '<%=HTTPContext.Current.User.Identity.Name %>'

但它不起作用,但是当我在标签之外写这个时,例如:

<h2>
<%=HTTPContext.Current.User.Identity.Name %>
</h2>

有用。

4

3 回答 3

4
<asp:Label ID="lbUserName" 
           runat="server"
           Text='<%# HttpContext.Current.User.Identity.Name %>'
            />

在 Page_Load

if (!Page.IsPostBack )
{
   lbUserName.DataBind();
}
于 2012-03-20T12:35:12.660 回答
1

像这样使用标签

<asp:label id="lblx" runat="server" ><%= HTTPContext.Current.User.Identity.Name %></asp:label>
于 2012-03-20T12:38:43.633 回答
1

要像这样绑定文本,您必须创建自己的自定义表达式构建器。

首先,将此类添加到您的命名空间:

using System.Web.Compilation;
using System.CodeDom;

[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder
{
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
        object parsedData, ExpressionBuilderContext context)
    {
        return new CodeSnippetExpression(entry.Expression);
    }
}

下一步是将其添加到您的 web.config 文件中:

<compilation debug="true">
    <expressionBuilders>
        <add expressionPrefix="Code" type="YourNameSpace.CodeExpressionBuilder"/>
    </expressionBuilders>
</compilation>

然后最后这应该工作:

<asp:Label id="YourLabel" runat="server" Text='<%$ Code:HttpContext.Current.User.Identity.Name %>' />

实现简单事情的复杂方法,但这将允许您在整个项目中使用您想要的语法,因此可能值得付出额外的努力。

参考

于 2012-03-20T12:50:00.340 回答