wingman007 icon

2018_DotNetProgrammingPartTime_Edit.cshtml.cs

wingman007 | PRO | 09/25/18 11:54:08 AM UTC | 0 ⭐ | 826 👁️ | Never ⏰ | []
C# |

1.33 KB

|

None

|

0 👍

/

0 👎

?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;
 
namespace WebApplication1bDeletMe.Pages
{
    public class EditModel : PageModel
    {
        private readonly AppDbContext _db;
 
        public EditModel(AppDbContext db)
        {
            _db = db;
        }
 
        [BindProperty]
        public Customer Customer { get; set; }
 
        public async Task<IActionResult> OnGetAsync(int id)
        {
            Customer = await _db.Customers.FindAsync(id);
 
            if (Customer == null)
            {
                return RedirectToPage("/Index");
            }
 
            return Page();
        }
 
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
 
            _db.Attach(Customer).State = EntityState.Modified;
 
            try
            {
                await _db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                throw new Exception($"Customer {Customer.Id} not found!");
            }
 
            return RedirectToPage("/Index");
        }
    }
}

Comments