首页 > 解决方案 > 如何仅在 ASP.NET MVC 中仅显示当前登录用户创建的项目

问题描述

正如问题所说,我试图弄清楚我将如何做到这一点,所以当用户登录时,他们只会看到他们输入数据库的数据条目。我使用 ASP.NET Core Web App (Model-View_Controller) 模板来启动。

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(){

       

    }

}

这是有问题的数据,项目模型。我最初的想法是我需要在 AspNetUsers 表和 Items 表之间建立一对多的关系,然后在 items 控制器中更改某些内容,但我不完全确定如何/是否可以对 AspNetUsers 表进行编辑。

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

这是项目控制器。如果我需要提供更多信息,我可以。

标签: c#asp.netasp.net-mvcasp.net-coreasp.net-mvc-4

解决方案


但我不完全确定如何/是否可以对 AspNetUsers 表进行编辑。

IdentityUser您可以从自定义用户数据继承。

这是您可以遵循的工作演示:

模型:

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

控制器:

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

数据库上下文:

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

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

启动.cs:

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

更新Pages/Shared/_LoginPartial.cshtml并替换IdentityUserApplicationUser

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

结果:

在此处输入图像描述


推荐阅读