周围有很多不错的博客文章,都在谈论这个非常具体的话题。我会简要介绍一下如何以及从何处开始。
我在这里将 John Attens 示例帖子设为 reference。
既然你已经有了一个User 类,你可以直接进入你的AccountController 并实现一个索引方法。您希望首先显示所有用户,以便选择要删除的用户。
[Authorize(Roles = "Admin")]
public ActionResult Index()
{
var Db = new ApplicationDbContext();
var users = Db.Users;
//ViewModel will be posted at the end of the answer
var model = new List<EditUserViewModel>();
foreach(var user in users)
{
var u = new EditUserViewModel(user);
model.Add(u);
}
return View(model);
}
您可以从那里实现删除方法(GET 和 POST):
[Authorize(Roles = "Admin")]
public ActionResult Delete(string id = null)
{
var Db = new ApplicationDbContext();
var user = Db.Users.First(u => u.UserName == id);
var model = new EditUserViewModel(user);
if (user == null)
{
return HttpNotFound();
}
return View(model);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
public ActionResult DeleteConfirmed(string id)
{
var Db = new ApplicationDbContext();
var user = Db.Users.First(u => u.UserName == id);
Db.Users.Remove(user);
Db.SaveChanges();
return RedirectToAction("Index");
}
EditUserViewModel
public class EditUserViewModel
{
public EditUserViewModel() { }
// Allow Initialization with an instance of ApplicationUser:
public EditUserViewModel(ApplicationUser user)
{
this.UserName = user.UserName;
this.FirstName = user.FirstName;
this.LastName = user.LastName;
this.Email = user.Email;
}
[Required]
[Display(Name = "User Name")]
public string UserName { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
//you might want to implement jobs too, if you want to display them in your index view
}
*再次:这不是我自己的代码。这是 John Atten 在http://typecastexception.com 写的一个例子。 *