ASP.NET Core MVC 中索引视图中只显示当前用户登录的记录?

问题描述 投票:0回答:1

如何在索引视图中显示当前登录用户的记录?我不想让他们看到其他用户的记录,我只想让他们看到自己在数据库中添加的记录。我已经实现了身份认证和验证,以便用户可以拥有自己的帐户。请帮我修改我的代码。我看不到任何有关此问题的资源。我没有 ApplicationUser 所以我使用 IdentityUser 代替。

这是我当前的班级模型:

 public class CommitmentForm
 {
    [Key]
    public int CommitmentId { get; set; }

    [Required]
    public string? OrganizationName { get; set; }

    [Required]
    public string? AdvicerName { get; set; }

    [Required]
    public string? HomeAddress { get; set; }

    [Required]
    public string? ContactNo { get; set; }

    public int CollegeId { get; set; }
    [ForeignKey("CollegeId")]
    [ValidateNever]
    public College College { get; set; }

    public int AcademicRankId { get; set; }
    [ForeignKey("AcademicRankId")]
    [ValidateNever]
    public AcademicRank AcademicRank { get; set; }

    [Display(Name = "School Year")]
    public int SchoolYear { get; set; } = DateTime.Now.Year;
 }

这是我当前的视图模型:

public class CommitmentFormVM
{
    public CommitmentForm CommitmentForm { get; set; }

    [ValidateNever]
    public IEnumerable<SelectListItem> CollegeList { get; set; }
    [ValidateNever]
    public IEnumerable<SelectListItem> AcademicRankList { get; set; }
}

这是我的控制器操作:

public class CommitmentFormController : Controller
{
    private readonly ApplicationDbContext _db;
    private readonly IUnitOfWork _unitOfWork;
    private readonly UserManager<IdentityUser> _userManager;

    public CommitmentFormController(ApplicationDbContext db, IUnitOfWork unitOfWork, UserManager<IdentityUser> userManager)
    {
        _db = db;
        _unitOfWork = unitOfWork;
        _userManager = userManager;
    }

    //public IActionResult Index()
    //{
    //    string userId = Commonism.getUserId(this.User);

    //    var User = _db.Users.SingleOrDefault(m => m.Id == userId);

    //    if (User == null)
    //    {
    //        return NotFound();
    //    }

    //    var currentUserCommitments = _db.CommitmentForms.Where(u => u.UserId == userId).ToList();

    //    return View(currentUserCommitments);
    //}

    [HttpGet]
    public IActionResult Details(int? id)
    {
        if (id == null || _unitOfWork.Commitment == null)
        {
            return NotFound();
        }

        var commitmentObj = _unitOfWork.Commitment.Get(u => u.CommitmentId == id, includeProperties: "College,AcademicRank");

        if (commitmentObj == null)
        {
            return NotFound();
        }

        return View(commitmentObj);
    }

    [HttpGet]
    public async Task<IActionResult> Upsert(int? id)
    {
        CommitmentFormVM cmVM = new CommitmentFormVM
        {
            CollegeList = _unitOfWork.College.
            GetAll().Select(u => new SelectListItem
            {
                Text = u.CollegeName,
                Value = u.CollegeId.ToString()
            }),

            AcademicRankList = _unitOfWork.AcademicRank.
            GetAll().Select(u => new SelectListItem
            {
                Text = u.RankName,
                Value = u.AcademicRankId.ToString()
            }),

            CommitmentForm = new CommitmentForm()
        };

        if (id == null || id == 0)
        {
            // create
            return View(cmVM);
        }
        else
        {
            // update
            cmVM.CommitmentForm = _unitOfWork.Commitment.Get(u => u.CommitmentId == id);
            return View(cmVM);
        }
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Upsert(CommitmentFormVM commitmentFormVM)
    {
        if (ModelState.IsValid)
        {
            if (commitmentFormVM.CommitmentForm.CommitmentId == 0)
            {
                _unitOfWork.Commitment.Add(commitmentFormVM.CommitmentForm);
                TempData["success"] = "Commitment Form added successfully";
            }
            else
            {
                _unitOfWork.Commitment.Update(commitmentFormVM.CommitmentForm);
                TempData["success"] = "Commitment Form updated successfully";
            }
            _unitOfWork.SaveChanges();
            return RedirectToAction("Details", new { id = commitmentFormVM.CommitmentForm.CommitmentId });
        }
        else
        {
            commitmentFormVM.CollegeList = _unitOfWork.College.
            GetAll().Select(u => new SelectListItem
            {
                Text = u.CollegeName,
                Value = u.CollegeId.ToString()
            });
            commitmentFormVM.AcademicRankList = _unitOfWork.AcademicRank.
            GetAll().Select(u => new SelectListItem
            {
                Text = u.RankName,
                Value = u.AcademicRankId.ToString()
            });

            return View(commitmentFormVM);
        }         
    }

    public IActionResult Delete(int? id)
    {
        CommitmentFormVM cmVM = new()
        {
            CollegeList = _unitOfWork.College.
            GetAll().Select(u => new SelectListItem
            {
                Text = u.CollegeName,
                Value = u.CollegeId.ToString()
            }),
            AcademicRankList = _unitOfWork.AcademicRank.
            GetAll().Select(u => new SelectListItem
            {
                Text = u.RankName,
                Value = u.AcademicRankId.ToString()
            }),
            CommitmentForm = new CommitmentForm(),
        };

        // delete
        cmVM.CommitmentForm = _unitOfWork.Commitment.Get(u => u.CommitmentId == id);
        return View(cmVM);
        
    }

    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public IActionResult DeleteCategory(int? id)
    {
        if (_unitOfWork == null)
        {
            return Problem("Entity set 'IUnitOfWork'  is null.");
        }
        CommitmentForm? category = _unitOfWork.Commitment.Get(u => u.CommitmentId == id);
        if (category != null)
        {
            _unitOfWork.Commitment.Remove(category);
        }

        _unitOfWork.SaveChanges();
        TempData["success"] = "Commitment Form deleted successfully"; //for toaster before redirecting
        return RedirectToAction("Index", "Home");
    }

}

我评论了索引操作,因为我不知道该怎么做。

如果我需要更改其中的某些内容,这是我的更新插入视图:

@model CommitmentFormVM;

<div class="college-create-container" style="margin-top:10rem">

    <div class="cf-form-container">

        <div class="cf-logo-container">
            @(Model.CommitmentForm.CommitmentId != 0 ? "Update" : "Create") Commitment Form
        </div>

        <form method="post" class="cf-form">
            <input asp-for="CommitmentForm.CommitmentId" hidden />

            <div class="cf-form-group">
                <label for="orgName">Organization Name</label>
                <input asp-for="CommitmentForm.OrganizationName" type="text" id="orgName" placeholder="College Name">
                <span asp-validation-for="CommitmentForm.OrganizationName" class="text-danger"></span>
            </div>

            <div class="cf-form-group">
                <label for="advName">Advicer Name</label>
                <input asp-for="CommitmentForm.AdvicerName" type="text" id="advName" placeholder="College Name">
                <span asp-validation-for="CommitmentForm.AdvicerName" class="text-danger"></span>
            </div>

            <div class="cf-form-group">
                <label for="address">Home Address</label>
                <input asp-for="CommitmentForm.HomeAddress" type="text" id="address" placeholder="College Name">
                <span asp-validation-for="CommitmentForm.HomeAddress" class="text-danger"></span>
            </div>

            <div class="cf-form-group">
                <label for="cn">Contact Number</label>
                <input asp-for="CommitmentForm.ContactNo" type="text" id="cn" placeholder="College Name">
                <span asp-validation-for="CommitmentForm.ContactNo" class="text-danger"></span>
            </div>

            <div class="cf-form-group">
                <label for="sy">School Year</label>
                <input asp-for="CommitmentForm.SchoolYear" type="text" id="sy" disabled>
                <span asp-validation-for="CommitmentForm.SchoolYear" class="text-danger"></span>
            </div>

            <div class="cf-row">
                <div class="cf-form-group">
                    <label for="college">College</label>
                    <select asp-for="@Model.CommitmentForm.CollegeId" asp-items="@Model.CollegeList" id="college" class="form-select">
                        <option disabled selected>--Select College--</option>
                    </select>
                    <span asp-validation-for="CommitmentForm.CollegeId" class="text-danger"></span>
                </div>

                <div class="cf-form-group">
                    <label for="ar">Academic Rank</label>
                    <select asp-for="@Model.CommitmentForm.AcademicRankId" asp-items="@Model.AcademicRankList" id="ar" class="form-select">
                        <option disabled selected>--Select Academic Rank--</option>
                    </select>
                    <span asp-validation-for="CommitmentForm.AcademicRankId" class="text-danger"></span>
                </div>
            </div>

            @if(Model.CommitmentForm.CommitmentId != 0)
            {
                <button class="cf-form-submit-btn" type="submit">Update</button>
            }
            else
            {
                <button class="cf-form-submit-btn" type="submit">Submit</button>
            }
        </form>

    </div>

</div>

(我已经获取当前登录的用户ID并显示在表单中。在我单击提交按钮之前它是可见的,但之后,userId消失,这导致

modelstate.isValid
为假并且无法继续索引看法) 上面的代码在 upsert httppost 直接到详细信息操作中,因为我仍然没有索引视图,但我想要的是在创建记录后首先将它们导航到索引,在那里他们可以看到自己创建的记录。

(我希望用户创建记录后,他们将导航到索引视图,其中显示他们自己创建的记录的列表。他们不应该看到其他用户的记录)

c# sql-server asp.net-core asp.net-core-mvc filtering
1个回答
0
投票

首先,您应该确保CommitmentForm和ApplicationUser(自定义身份用户)之间存在一对一或一对多的关系。

如下:

公开课承诺表 { [钥匙] 公共 int CommitmentId { 获取;放; }

[Required]
public string? OrganizationName { get; set; }

[Required]
public string? AdvicerName { get; set; }

[Required]
public string? HomeAddress { get; set; }

[Required]
public string? ContactNo { get; set; }

public int CollegeId { get; set; }
[ForeignKey("CollegeId")]
[ValidateNever]
public College College { get; set; }

public int AcademicRankId { get; set; }
[ForeignKey("AcademicRankId")]
[ValidateNever]
public AcademicRank AcademicRank { get; set; }

[Display(Name = "School Year")]
public int SchoolYear { get; set; } = DateTime.Now.Year;

public ApplicationUser IdentityUser { get; set; }

}

然后您可以创建一个自定义身份用户,如下所示:

创建一个新类:

  public class ApplicationUser : IdentityUser
  {
      public CommitmentForm CommitmentForm { get; set; }
  }

修改dbcontext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
     public DbSet<CommitmentForm> CommitmentForms { get; set; }
}

然后修改程序.cs:

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

然后我们就有了这两个类的关系。

然后在视图中,您可以查询索引视图的 ID,如下所示:

    private readonly ILogger<HomeController> _logger;

    private readonly ApplicationDbContext _db;
 


    public HomeController(ILogger<HomeController> logger, ApplicationDbContext db)
    {
        _logger = logger;
        _db = db;
     
    }

    public IActionResult Index()
    {
        var currentUserCommitments = new List<CommitmentForm>();
        if (User.Identity.IsAuthenticated)
        {
           currentUserCommitments = _db.CommitmentForms.Where(u => u.IdentityUser.UserName ==  User.Identity

.名称).ToList(); }

        return View(currentUserCommitments);
    }

然后对于模型验证失败的问题,您需要使用调试工具来调试哪个属性导致模型失败,如果CommitmentFormVM内部需要触发一些属性,例如应用程序用户ID,您可以创建一个隐藏字段来存储它。

<input type="hidden" asp-for="CommitmentForm.IdentityUser.Id"/>
© www.soinside.com 2019 - 2024. All rights reserved.