我有一个通过SqlDataSource
绑定AspNetUsers
GridView
。 我正在尝试实现删除和编辑/更新用户的GridView_RowCommand
,但我无法弄清楚如何通过 ASP.NET 身份 API 做到这一点。 我用一个名为 ApplicationUser
的类扩展了IdentityUser
,我的数据库上下文称为 ApplicationDBContext
。
当我在 GridView 行上单击"删除"或"编辑"时,如何在给定所选用户的情况下删除或更新用户。
这是我到目前为止所拥有的,但基本上什么都没有:
protected void Users_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
//How do I delete?
}
else if(e.CommandName == "Edit")
{
How do I Update?
}
}
这是我整理的一个例子,我没有Visual Studio,所以它可能不是100%,但它足够接近你的目的,我会说:
protected void Users_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int id = Convert.ToInt32(Users.DataKeys[e.RowIndex].Value);
ApplicationUser user = (ApplicationUser)IdentityManager.Store.Users.FindAsync(id, CancellationToken.None);
using (ApplicationDbContext dbcontext = new ApplicationDbContext())
{
dbcontext.UserLogins.RemoveRange(dbcontext.UserLogins.Where(ul => ul.UserId == user.Id));
dbcontext.UserRoles.RemoveRange(dbcontext.UserRoles.Where(ur => ur.UserId == user.Id));
dbcontext.UserSecrets.RemoveRange(dbcontext.UserSecrets.Where(us => us.UserName == user.UserName));
dbcontext.UserManagement.RemoveRange(dbcontext.UserManagement.Where(um => um.UserId == user.Id));
dbcontext.Users.Remove(dbcontext.Users.Where(usr => usr.Id == user.Id).Single());
dbcontext.SaveChanges();
}
}
}
起初我尝试了GridView的RowCommand,它被触发了,但后来我最终在SqlDataSource上指定了DeleteCommand和UpdateCommand,这解决了这个问题。
唯一的更改是在我配置 SqlDataSource 时进行的,该源生成以下标记,这反过来又使事情正常工作:
<asp:SqlDataSource ID="UsersSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
SelectCommand="SELECT [Id], [UserName], [FirstName], [LastName], [Email] FROM [AspNetUsers]"
DeleteCommand="DELETE FROM [AspNetUsers] WHERE [Id] = @Id"
InsertCommand="INSERT INTO [AspNetUsers] ([Id], [UserName], [FirstName], [LastName], [Email]) VALUES (@Id, @UserName, @FirstName, @LastName, @Email)"
UpdateCommand="UPDATE [AspNetUsers] SET [UserName] = @UserName, [FirstName] = @FirstName, [LastName] = @LastName, [Email] = @Email WHERE [Id] = @Id">
<DeleteParameters>
<asp:Parameter Name="Id" Type="String" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Id" Type="String" />
<asp:Parameter Name="UserName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="Email" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="UserName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="Id" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>