Skip to main content
 首页 » 编程设计

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

2024年02月23日14lidabo

我正在使用 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 
  } 
} 
}