c# - 当前上下文中不存在名称 xxx

标签 c# asp.net controls

我正在使用 asp.net 的登录控件和 Fileuploader。 当我将文件 uploader 控件留在 <LoggedInTemplate> 之外时它有效,但是当我尝试将 Fileuploader 移动到 <LoggedInTemplate> 中时我收到“名称 xxx 在当前上下文中不存在”,它指的是 C#。

<LoggedInTemplate>
    <b>Login ok ! </b><br />
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        InsertCommand="INSERT INTO aspnet_PicturesHome(pUrl) VALUES (@pUrl)"
        SelectCommand="SELECT pID, pUrl FROM aspnet_PicturesHome">
            <InsertParameters>
                <asp:ControlParameter Name="pUrl" Type="String" ControlID="FileUpload1" PropertyName="FileName"/>
            </InsertParameters>
        </asp:SqlDataSource>
<asp:Label ID="Label1" runat="server" Text="Label">Foto upload: </asp:Label>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
<br></br>
</LoggedInTemplate>

最佳答案

主要编辑:您可以访问嵌套在 LoginView 中的控件像这样:

FileUpload fu = LoginView1.FindControl("FileUpload1") as FileUpload;

如果它们在 <LoggedInTemplate> 中,您需要确保它们确实已登录(反之亦然,以访问 <AnonymousTemplate> 中的控件:它们不应登录),否则它将找不到控件和 .FindControl()将返回 null .

引用:
http://www.velocityreviews.com/forums/t109239-accessing-a-control-within-loginview.html

根据评论编辑:在您的Page_Load() ,如果初始请求(不是回发)检查用户是否是管理员,如果不是,则禁用上传控件

protected void Page_Load(object sender, EventArgs e){

if(!this.isPostBack)
{
  if(!Context.User.IsInRole("admin"))
  {
     //disable controls
  }
}
}

关于c# - 当前上下文中不存在名称 xxx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7699108/

相关文章:

python pygame 输入控件

c# - 在 c# 中重新创建 Az.Connect-AzAccount

c# - C# 中的 GetType() 和 Typeof()

c# - 有没有关于在没有默认 ASP.Net 成员提供程序的情况下创建 MVC3 登录系统的教程?

asp.net - 如何在单元测试中使用Redis?

asp.net - 从 GridView 中的 2 列动态生成超链接

c# - 字典联合到字典?

c# - 同一列中包含多个信息的 DataGridview

c# - 如何在 TrackBar 中使用 float

winapi - 如何通过 OCM_ 消息处理未处理的 Win32 消息反射到子级控件