在SQL Server中删除用户

时间:2016-01-04 10:11:39

标签: sql sql-server asp.net-mvc

我正在尝试创建一个管理员区域,管理员可以从dbo.AspNetUsers删除用户。到目前为止,我在管理员控制器的索引视图中有这个:

@using BlogMaxim.Models
@model List<BlogMaxim.Models.Users>
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@foreach (Users user in Model)
{
    <div class="table-responsive">
        <table class="table table-condensed">
            <tr>
                <th>Username</th>
                <th>Email</th>
                <th>Id</th>
            </tr>
            <tr>
                <td>@user.UserName</td>
                <td>@user.Email</td>
                <td>@user.Id</td>
                <td>@using (Html.BeginForm("Delete", "Admin", new { id = user.Id }))
                {
                    <input type="submit" class="button" value="Delete" />
                }</td>
            </tr>
        </table>
    </div>

}

它会显示所有用户以及旁边的删除按钮。我不知道我需要在admincontroller的Delete方法中编写哪些代码:

public class AdminController : Controller
{
    private UserRepository repoUsers = new UserRepository();

    // GET: Admin
    [Authorize(Roles = "Admin")]
    public ActionResult Index()
    {
        List<Users> users = repoUsers.GetUsers();
        return View(users);
    }

    public ActionResult Delete()
    {
        return RedirectToAction("Index");
    }
}

这就是我现在所拥有的,我是ASP.NET MVC的新手。

2 个答案:

答案 0 :(得分:1)

如果您使用的是EF,则更简单:

[HttpPost]
public ActionResult Delete(int Id)
{
    private ApplicationDbContext context = new ApplicationDbContext();  
    var user = context.Users.Find(Id);
    context.Users.Remove(user);
    context.SaveChanges();
    return RedirectToAction("Index");
}

其中ApplicationDbContext是置于Models文件夹中IdentityModels.cs中的IdentityDbContext的子类

答案 1 :(得分:0)

创建dbEntities类 -

public partial class dbEntities : DbContext
    {
        public dbEntities()
            : base("name=the name of the database that you have given in connectionstring")
        {
        }
}

在控制器中 -

private readonly dbEntities database;
 public AdminController ()
        {
            this.database = new dbEntities();
        }

然后在你的ActionResult of Delete

public ActionResult Delete(int Id)
{
    ABC abc = new ABC();
    abc = db.ABC.Find(Id);
    database.Remove(abc);
    database.SaveChanges();
    return RedirectToAction("Index");
}