我有GridView
通过AspNetUsers
绑定到SqlDataSource
。我正在尝试实现GridView_RowCommand
删除和编辑/更新用户,但我无法弄清楚如何通过ASP.NET Identity API来实现。我使用名为IdentityUser
的类扩展了ApplicationUser
,并将我的数据库上下文称为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?
}
}
答案 0 :(得分:-1)
这是我放在一起的一个例子,我没有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();
}
}
}
答案 1 :(得分:-1)
起初我尝试了触发的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>