尝试获取当前登录的用户userid并在后面的代码中使用它来填充gridview,但它没有任何想法,我做错了什么。我一直得到一个空值错误。此外,我试图只使用Microsoft.AspNet.Identity,如果那可能
页面加载
if (!IsPostBack)
{
SqlDataSource SqlDataSource1 = new SqlDataSource();
SqlDataSource1.ID = "SqlDataSource1";
this.Page.Controls.Add(SqlDataSource1);
SqlDataSource1.InsertParameters["luser"].DefaultValue = User.Identity.GetUserId();
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlDataSource1.SelectCommand = "SELECT top 3 UserId, Friending from Friendreq Where Friending = @luser";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
更新:
通过将请求直接添加到SQL查询中,我能够获得我想要的结果。有什么理由我不应该添加什么
SqlDataSource SqlDataSource1 = new SqlDataSource();
SqlDataSource1.ID = "SqlDataSource1";
this.Page.Controls.Add(SqlDataSource1);
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlDataSource1.SelectCommand = "SELECT top 3 UserId, Friending from Friendreq Where Friending = '"+User.Identity.GetUserId()+"'";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
解决方案= Friending = '"+User.Identity.GetUserId()+"'";
答案 0 :(得分:1)
如果尝试从HttpContext获取用户身份,请尝试使用以下代码。身份存储用户名/ id(基于您的逻辑)在Name属性中。
此外,对象引用错误即将发生,因为您尚未添加" luser"在InsertParameter中,但尝试为其设置默认值。我已添加此SqlDataSource1.InsertParameters.Add(new Parameter("luser"));
以确保它在使用之前具有参数
if (!IsPostBack)
{
SqlDataSource SqlDataSource1 = new SqlDataSource();
SqlDataSource1.ID = "SqlDataSource1";
this.Page.Controls.Add(SqlDataSource1);
SqlDataSource1.InsertParameters.Add(new Parameter("luser"));
SqlDataSource1.InsertParameters["luser"].DefaultValue = HttpContext.Current.User.Identity.IsAuthenticated ? HttpContext.Current.User.Identity.Name : String.Empty;
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlDataSource1.SelectCommand = "SELECT top 3 UserId, Friending from Friendreq Where Friending = @luser";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}