SqlDataSource不会从数据库中检索登录用户的数据?

时间:2013-01-19 13:34:04

标签: asp.net sql-server asp.net-membership sqldatasource

我尝试根据登录的UserId检索用户的数据,但没有进展。有什么建议吗?

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    // Get a reference to the currently logged on user  
    MembershipUser currentUser = Membership.GetUser();    

    // Determine the currently logged on user's UserId value   
    Guid currentUserId = (Guid)currentUser.ProviderUserKey;   

    // Assign the currently logged on user's UserId to the @UserId parameter     
    e.Command.Parameters["@UserId"].Value = currentUserId; 
}

这是SqlDataSource

  <asp:SqlDataSource ID="SqlDataSource1" runat="server"
      ConnectionString='<%$ ConnectionStrings:NaviConnectionString %>' 
    SelectCommand="SELECT [UserId], [FirstName], [LastName] FROM [UserProfiles] WHERE ([UserId]  = @UserId)">
    <SelectParameters>
        <asp:Parameter Name="UserId" Type="String"></asp:Parameter>
    </SelectParameters>
  </asp:SqlDataSource>

这是GridView

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
               DataKFFeyNames="UserId" DataSourceID="SqlDataSource1" 
               EmptyDataText="There are no data records to display." 
               DataKeyNames="UserId">
     <Columns>
         <asp:BoundField DataField="UserId" HeaderText="UserId" SortExpression="UserId" />
         <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
         <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
     </Columns>
</asp:GridView>

没有要显示的数据记录。

enter image description here

但是,当我在查询构建器中执行代码时,它可以正常工作。

所以我需要从数据库中手动获取UserId

enter image description here

然后转到查询构建器,然后执行,然后将userid粘贴到UserID的值。

enter image description here

然后它会根据UserId

显示正确的数据

enter image description here

我也尝试将其更改为:

  <SelectParameters>
        <asp:Parameter Name="UserId" Type="Empty" DbType="Guid"></asp:Parameter>
  </SelectParameters>

3 个答案:

答案 0 :(得分:1)

您应该设置一个断点,看看是否填充了currentUserId。我相信它是。如果是这样,那么检索UserId不是问题,而是问题是设置参数值或选择数据。

我认为您需要将参数类型从字符串更改为 Guid

<SelectParameters>
    <asp:Parameter Name="UserId" Type="Guid"></asp:Parameter>
</SelectParameters>

答案 1 :(得分:0)

只需更改此内容:

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)

{

// Get a reference to the currently logged on user  
   MembershipUser currentUser = Membership.GetUser();    

// Determine the currently logged on user's UserId value   
Guid currentUserId = (Guid)currentUser.ProviderUserKey;   

// Assign the currently logged on user's UserId to the @UserId parameter     
e.Command.Parameters["@UserId"].Value = currentUserId.ToString();
}

答案 2 :(得分:0)

在参数类型中没有guid选项。 (另外在上面的代码中sql数据源还没有设置SqlDataSource1_Selecting。)怎么回答?只需声明参数名称即可。

<asp:Parameter Name="UserId"></asp:Parameter>