using _2021_backend.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace _2021_backend.Pages.Students { public class CreateModel : PageModel { private readonly _2021_backend.Data.BackendContext Context; public CreateModel(_2021_backend.Data.BackendContext context) { Context = context; } public IActionResult OnGet() { Student = new Student(); return Page(); } [BindProperty] [Required(ErrorMessage = "该项不能为空")] public Student Student { get; set; } // To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD public async Task OnPostAsync() { if (!ModelState.IsValid) { return Page(); } if (Context.Students.Any(t => (t.Name == Student.Name || t.Stuid == Student.Stuid || t.Tel == Student.Tel))) { return RedirectToPage("./Index", new { pageId = 0, errInfo = "该学生已经存在" }); } Context.Students.Add(Student); await Context.SaveChangesAsync(); return RedirectToPage("./Index"); } } }