c# - 尝试更改 asp.net 中默认 login.aspx 页面内的标签文本

标签 c# asp.net authentication label

我正在尝试更改我在 .net 4.0 中创建新网站时提供给您的默认 login.aspx 页面内创建的标签文本。我似乎无法以任何方式访问此标签。如果用户未获批准,则单击登录按钮时文本应该会更改。这是制作标签的地方。

    <LayoutTemplate>
        <span class="failureNotification">
            <asp:Literal ID="FailureText" runat="server"></asp:Literal>
        </span>
        <asp:ValidationSummary ID="LoginUserValidationSummary" runat="server" CssClass="failureNotification" 
             ValidationGroup="LoginUserValidationGroup"/>
             <%-- If the account is not approved display an error message --%>
        <asp:Label ID="NotAproved" runat="server" CssClass="failureNotification"></asp:Label>......

我曾尝试使用 FindControl 访问它,但它从来没有用过,所以我可能做错了什么。预先感谢您的帮助。

编辑: 我在后面的代码中找到了访问它的方法,以防万一有人有类似的问题:

    var notApproved = (Label)LoginUser.FindControl("NotApproved");
    notApproved.Text = "Sorry Your Account has not yet Been Approved by an Administrator. Try Again Later.";

最佳答案

FindControl 方法只会找到作为您正在搜索的容器的直接后代 的服务器端控件(在本例中)。来自 MSDN(我已经强调)-

Use FindControl to access a control from a function in a code-behind page, to access a control that is inside another container, or in other circumstances where the target control is not directly accessible to the caller. This method will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls. For information about how to find a control when you do not know its immediate container, see How to: Access Server Controls by ID.

http://msdn.microsoft.com/en-us/library/486wc64h.aspx

通常,您应该避免使用 FindControl 并使用 ID 直接引用控件,以便返回强类型对象并避免对特定控件层次结构的紧密依赖,但这对于在模板中添加的控件是不可能的,因为您有可能找到了。

看来您是偶然发现或自己解决了直系后代要求,但我建议以下代码可能更安全-

var notApproved = LoginUser.FindControl("NotApproved") as Label;
if (notApproved != null)
{
    notApproved.Text = "Sorry Your Account has not yet Been Approved by an Administrator. Try Again Later.";
}

如果 LoginUser.FindControl("NotApproved") 没有找到任何东西并返回 Null(请参阅上面的 MSDN 链接),这会处理您将得到的 NullReferenceException 以及一个可能的类型转换异常,其中找到的对象不是标签并且不能转换为一个。

关于c# - 尝试更改 asp.net 中默认 login.aspx 页面内的标签文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17156992/

相关文章:

cookies - 您可以延长 BC 中登录的 Cookie 持续时间吗?

java - 监听所有请求 Tomcat

c# - Entity Framework TPH 在抽象基类和空继承类场景中更改鉴别器列

c# - Squirrel 没有创建快捷方式所针对的 .exe

c# - 上传任何视频并在 .net 中在线转换为 .mp4

asp.net - ASP .NET session 状态的 'InProc' 与 'StateServer' 的最佳实践

asp.net - 如何将ASP.NET MVC5身份验证添加到现有数据库

asp.net - 实体类型 'Customer' 无法映射到表,因为它是从 'ApplicationUser' 派生的

node.js - 如何将 REST API 限制为用户特定的内容

c# - 使用 Json.NET/NEST/Elasticsearch 在 ASP.NET Core 应用程序中找不到方法错误