Home > Net >  How to only display items created by the current logged in user only in ASP.NET MVC
How to only display items created by the current logged in user only in ASP.NET MVC

Time:09-17

As the question says I'm trying to figure out exactly how I would make it so when a user logs in they only see the data entries they have entered into the database. I used the ASP.NET Core Web App (Model-View_Controller) template to start.

public class Item
{

    public int Id { get; set; }

    public string Name { get; set; }
    public string Description { get; set; }
    public string Power { get; set; }
    public string Charges { get; set; }

    public Item(){

       

    }

}

This is the data in question, the items model. My initial thought was that I need a one to many relationship between the AspNetUsers table and the Items table and then change something in the items controller, but I'm not entirely sure how/if I can make edits to the AspNetUsers table.

public class ItemsController : Controller
{
    private readonly ApplicationDbContext _context;

    public ItemsController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: Items
    public async Task<IActionResult> Index()
    {
        //Return a list to the view
        return View(await _context.Item.ToListAsync());
    }

    public async Task<IActionResult> SearchItems()
    {
        return View();
    }

    public async Task<IActionResult> ShowSearchResults(String SearchPhrase)
    {
        //Return a list from index where 
        return View("Index", await _context.Item.Where(j => j.Name.Contains(SearchPhrase)).ToListAsync());
    }

    // GET: Items/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var item = await _context.Item
            .FirstOrDefaultAsync(m => m.Id == id);
        if (item == null)
        {
            return NotFound();
        }

        return View(item);
    }

    // GET: Items/Create
    [Authorize]
    public IActionResult Create()
    {
        return View();
    }

    // POST: Items/Create
    // To protect from overposting attacks, enable the specific properties you want to bind to, for 
    // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    [Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,Name,Description,Power,Charges")] Item item)
    {
        if (ModelState.IsValid)
        {
            _context.Add(item);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(item);
    }

    // GET: Items/Edit/5
    [Authorize]
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var item = await _context.Item.FindAsync(id);
        if (item == null)
        {
            return NotFound();
        }
        return View(item);
    }

    // POST: Items/Edit/5
    // To protect from overposting attacks, enable the specific properties you want to bind to, for 
    // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    [Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Description,Power,Charges")] Item item)
    {
        if (id != item.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(item);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ItemExists(item.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(item);
    }

    // GET: Items/Delete/5
    [Authorize]
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var item = await _context.Item
            .FirstOrDefaultAsync(m => m.Id == id);
        if (item == null)
        {
            return NotFound();
        }

        return View(item);
    }

    // POST: Items/Delete/5
    [Authorize]
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var item = await _context.Item.FindAsync(id);
        _context.Item.Remove(item);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool ItemExists(int id)
    {
        return _context.Item.Any(e => e.Id == id);
    }

This is the items controller. If I need to give more information I can.

CodePudding user response:

but I'm not entirely sure how/if I can make edits to the AspNetUsers table.

You can inherit from IdentityUser to custom user data.

Here is a working demo you could follow:

Model:

public class ApplicationUser:IdentityUser
{
    public List<Item> Items { get; set; }
}
public class Item
{
    public int Id { get; set; }

    public string Name { get; set; }
    public string Description { get; set; }
    public string Power { get; set; }
    public string Charges { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
}

Controller:

public class ItemsController : Controller
{
    private readonly ApplicationDbContext _context;

    public ItemsController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: Items
    public async Task<IActionResult> Index()
    {
        var model = await _context.Item
                            .Where(a => a.ApplicationUser.Id == HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value)
                            .ToListAsync();
        return View(model);
    }
}

DbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Item> Item { get; set; }
}

Startup.cs:

services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();

Update Pages/Shared/_LoginPartial.cshtml and replace IdentityUser with ApplicationUser:

@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

Result:

enter image description here

  • Related