Files
PIBD-23_Coursach_YouAreProg…/YouAreProgrammerShop/YAPWebApplication/Pages/Views/Comments/Edit.cshtml.cs

80 lines
2.5 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using YAPContracts.BindingModels;
using YAPContracts.AdapterContracts;
using System.Security.Claims;
using DocumentFormat.OpenXml.Office2010.Excel;
namespace YAPWebApplication.Pages.Views.Comments
{
[Authorize(Roles = "Worker")]
public class EditModel : PageModel
{
private readonly ICommentAdapter _commentAdapter;
private readonly IProductSetAdapter _productSetAdapter;
public EditModel(ICommentAdapter commentAdapter, IProductSetAdapter productSetAdapter)
{
_commentAdapter = commentAdapter;
_productSetAdapter = productSetAdapter;
}
[BindProperty]
public CommentBindingModel Comment { get; set; } = default!;
public List<SelectListItem> ProductSetList { get; set; } = new();
private string? UserId { get; set; }
public IActionResult OnGet(string id)
{
if (id == null) return NotFound();
var comment = _commentAdapter.GetCommentById(id);
if (comment == null) return NotFound();
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (comment.AuthorId != userId)
return Forbid();
TempData["UserId"] = comment.AuthorId;
var sets = _productSetAdapter.GetList();
ProductSetList = sets?.Select(p => new SelectListItem
{
Value = p.Id,
Text = p.SetName,
Selected = (p.Id == comment.ProductSetId)
}).ToList() ?? new List<SelectListItem>();
Comment = new CommentBindingModel
{
Id = comment.Id,
Text = comment.Text,
ProductSetId = comment.ProductSetId,
Date = DateTime.UtcNow,
UserId = comment.AuthorId // can't change
};
return Page();
}
public IActionResult OnPost()
{
if (!ModelState.IsValid) return Page();
Comment.UserId = TempData["UserId"]?.ToString();
Comment.Date = DateTime.UtcNow;
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (Comment.UserId != userId)
return Forbid();
_commentAdapter.Update(Comment);
return RedirectToPage("./Index");
}
}
}