Files
abzarasadi/Pages/Admin/Blog/Edit.cshtml.cs
T

58 lines
2.1 KiB
C#
Raw Normal View History

2026-06-01 22:08:43 +03:30
using AsadiTools.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace AsadiTools.Pages.Admin.Blog;
[Authorize(AuthenticationSchemes = "AdminCookie")]
public class AdminBlogEditModel(AppDbContext db) : PageModel
{
[BindProperty] public BlogPostInput Input { get; set; } = new();
public int PostId { get; private set; }
public async Task<IActionResult> OnGetAsync(int id)
{
var post = await db.BlogPosts.FindAsync(id);
if (post is null) return NotFound();
PostId = id;
Input = new BlogPostInput
{
Title = post.Title,
Slug = post.Slug,
Content = post.Content,
Excerpt = post.Excerpt,
MetaDescription = post.MetaDescription,
FeaturedImage = post.FeaturedImage,
Tags = post.Tags,
IsPublished = post.IsPublished,
};
ViewData["Title"] = "ویرایش: " + post.Title;
return Page();
}
public async Task<IActionResult> OnPostAsync(int id)
{
if (!ModelState.IsValid) { PostId = id; return Page(); }
var post = await db.BlogPosts.FindAsync(id);
if (post is null) return NotFound();
var wasUnpublished = !post.IsPublished;
post.Title = Input.Title;
post.Slug = string.IsNullOrWhiteSpace(Input.Slug) ? post.Slug : Input.Slug.Trim();
post.Content = Input.Content;
post.Excerpt = Input.Excerpt;
post.MetaDescription = Input.MetaDescription;
post.FeaturedImage = string.IsNullOrWhiteSpace(Input.FeaturedImage) ? null : Input.FeaturedImage;
post.Tags = Input.Tags;
post.IsPublished = Input.IsPublished;
post.UpdatedAt = DateTime.Now;
if (Input.IsPublished && wasUnpublished)
post.PublishedAt = DateTime.Now;
await db.SaveChangesAsync();
return RedirectToPage("/Admin/Blog/Index");
}
}