using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using CoreWiki.Models; using CoreWiki.Utils; using NodaTime; namespace CoreWiki.Pages { public class CreateModel : PageModel { private readonly CoreWiki.Models.ApplicationDbContext _context; private readonly IClock _clock; public CreateModel(CoreWiki.Models.ApplicationDbContext context, IClock clock) { _context = context; _clock = clock; } public IActionResult OnGet() { return Page(); } [BindProperty] public Article Article { get; set; } = default!; public async Task OnPostAsync() { ModelState.Remove("Article.Slug"); if (!ModelState.IsValid) { return Page(); } Article.Slug = SafeUrl.Create(true, Article.Topic); Article.Published = _clock.GetCurrentInstant(); if (_context.Articles.Any(a => a.Slug == Article.Slug)) { ModelState.AddModelError("Article.Topic", "Article already exists"); return Page(); } _context.Articles.Add(Article); await _context.SaveChangesAsync(); return Redirect($"/{Article.Slug}"); } } }