Files
zpc-bulletin-board/ZpcBulletinBoard/Pages/Boards/AddEdit.cshtml.cs
2024-02-27 07:27:47 +01:00

111 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ZpcBulletinBoard.Data;
using ZpcBulletinBoard.Models;
using ZpcBulletinBoard.Models.Editor;
namespace ZpcBulletinBoard.Pages.Boards
{
//[Authorize(Roles = "Administrator,TransportThingUser,InvoicingUser")]
public class AddEditModel(ApplicationDbContext context)
//public class AddEditModel(ApplicationDbContext context, UserManager<IdentityApplicationUser> userManager)
: PageModel
{
[BindProperty]
public BulletinBoard Board { get; set; }
public async Task<IActionResult> OnGetAsync(Guid? guid)
{
//var user = userManager.GetUserAsync(User).Result;
if (guid == null)
{
Board = new BulletinBoard
{
Ratio = BulletinBoard.RatioEnum.Ratio16To9,
Guid = Guid.NewGuid(),
Pages = new List<BulletinBoardPage>()
};
return Page();
}
var tmpBoard = await context.BulletinBoards.Include(x => x.Pages)
.FirstOrDefaultAsync(m => m.Guid == guid);
if (tmpBoard == null)
{
return NotFound();
}
Board = tmpBoard;
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
System.Diagnostics.Debug.WriteLine("OnPost");
//var user = userManager.GetUserAsync(User).Result;
//Board.Notes = new List<Note>();
//if (!ModelState.IsValid)
//{
// System.Diagnostics.Debug.WriteLine(string.Join(",", ModelState.Where(a => a.Value.Errors.Count > 0)
// .Select(b => $"{b.Key} {b.Value.Errors}")));
// return Page();
//}
if (Board.IdBulletinBoard > 0)
{
context.Attach(Board).State = EntityState.Modified;
try
{
await context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!BoardExists(Board.IdBulletinBoard))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToPage("./Index");
}
// OrderNumber and OrderYear
context.BulletinBoards.Add(Board);
await context.SaveChangesAsync();
return RedirectToPage("./Index");
}
private bool BoardExists(int id)
{
return context.BulletinBoards.Any(e => e.IdBulletinBoard == id);
}
}
}