如何仅在 ASP.NET MVC 中显示当前登录用户创建的项目
How to only display items created by the current logged in user only in 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 table 和 Items table 之间的一对多关系,然后在 items 控制器中更改一些东西,但我不完全确定 how/if 我可以对 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);
}
这是项目控制器。如果我需要提供更多信息,我可以。
but I'm not entirely sure how/if I can make edits to the AspNetUsers table.
您可以从 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; }
}
Startup.cs:
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
更新 Pages/Shared/_LoginPartial.cshtml
并将 IdentityUser
替换为 ApplicationUser
:
@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
结果:
正如问题所说,我正试图弄清楚我将如何做到这一点,以便当用户登录时,他们只能看到他们输入到数据库中的数据条目。我使用 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 table 和 Items table 之间的一对多关系,然后在 items 控制器中更改一些东西,但我不完全确定 how/if 我可以对 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);
}
这是项目控制器。如果我需要提供更多信息,我可以。
but I'm not entirely sure how/if I can make edits to the AspNetUsers table.
您可以从 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; }
}
Startup.cs:
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
更新 Pages/Shared/_LoginPartial.cshtml
并将 IdentityUser
替换为 ApplicationUser
:
@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
结果: