Maxim
Maxim

Reputation: 631

Deleting User in SQL Server

I'm trying to create an admin area where the admin can delete a user from dbo.AspNetUsers. So far I have this in my index view from my admin controller:

@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>

}

It shows all the users along with a delete button next to it. I do not know what code I need to write in my admincontroller's Delete method:

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");
    }
}

This is what I have at this time, I'm rather new to ASP.NET MVC.

Upvotes: 1

Views: 177

Answers (2)

Awais Mahmood
Awais Mahmood

Reputation: 1336

If you are using EF then its more simpler as:

[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");
}

where ApplicationDbContext is the child class of IdentityDbContext placed in IdentityModels.cs in Models folder

Upvotes: 1

Nikita
Nikita

Reputation: 75

Create a dbEntities class-

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

In the controller -

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

Then in your 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");
}

Upvotes: 0

Related Questions