Silme işlemi için bir benzersiz değere ihtiyaç vardır. Bu bilgi yine URL üzerinde taşınabilir.
Öncelikle Delete.cshtml.cs dosyasını bir inceleyelim.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using RazorPagesMovie.Models; namespace RazorPagesMovie.Pages.Movies { public class DeleteModel : PageModel { private readonly RazorPagesMovie.Models.RazorPagesMovieContext _context; public DeleteModel(RazorPagesMovie.Models.RazorPagesMovieContext context) { _context = context; } [BindProperty] public Movie Movie { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } Movie = await _context.Movie.FirstOrDefaultAsync(m => m.ID == id); if (Movie == null) { return NotFound(); } return Page(); } public async Task<IActionResult> OnPostAsync(int? id) { if (id == null) { return NotFound(); } Movie = await _context.Movie.FindAsync(id); if (Movie != null) { _context.Movie.Remove(Movie); await _context.SaveChangesAsync(); } return RedirectToPage("./Index"); } } } |
OnGetAsync metodunda kayıt aranır ve kayıt bilgileri Delete.cshtml üzerine aktarılır ve sayfada gösterilir. Sayfadan bir POST işlemi geldiğinde OnPostAsync(int? id) metodu çalışır. Eğer URL üzerinde gelen id null değilse FindAsync kayıt aranır ve Movie nesnesi oluşturulur. Eğer Movie nesnesi boş değilse _Context içindeki Movie, Remove metodu ile silme harekete geçirilir. Daha sonra await _context.SaveChangesAsync() metodu ile silme işlemi fiziksel olarak ta gerçekleştirilir. Silme işlemi bittikten sonra Index sayfasına yönledirme söz konusudur.