Advertisement
wingman007

2018_DotNetProgrammingPartTime_Edit.cshtml.cs

Sep 25th, 2018
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.33 KB | None | 0 0
  1. ?using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.AspNetCore.Mvc.RazorPages;
  7. using Microsoft.EntityFrameworkCore;
  8.  
  9. namespace WebApplication1bDeletMe.Pages
  10. {
  11.     public class EditModel : PageModel
  12.     {
  13.         private readonly AppDbContext _db;
  14.  
  15.         public EditModel(AppDbContext db)
  16.         {
  17.             _db = db;
  18.         }
  19.  
  20.         [BindProperty]
  21.         public Customer Customer { get; set; }
  22.  
  23.         public async Task<IActionResult> OnGetAsync(int id)
  24.         {
  25.             Customer = await _db.Customers.FindAsync(id);
  26.  
  27.             if (Customer == null)
  28.             {
  29.                 return RedirectToPage("/Index");
  30.             }
  31.  
  32.             return Page();
  33.         }
  34.  
  35.         public async Task<IActionResult> OnPostAsync()
  36.         {
  37.             if (!ModelState.IsValid)
  38.             {
  39.                 return Page();
  40.             }
  41.  
  42.             _db.Attach(Customer).State = EntityState.Modified;
  43.  
  44.             try
  45.             {
  46.                 await _db.SaveChangesAsync();
  47.             }
  48.             catch (DbUpdateConcurrencyException)
  49.             {
  50.                 throw new Exception($"Customer {Customer.Id} not found!");
  51.             }
  52.  
  53.             return RedirectToPage("/Index");
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement