102 lines
3.1 KiB
C#
102 lines
3.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.RazorPages;
|
|
using Microsoft.AspNetCore.Mvc.Rendering;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using _2021_backend.Data;
|
|
using _2021_backend.Models;
|
|
|
|
namespace _2021_backend.Pages.Users
|
|
{
|
|
public class EditModel : PageModel
|
|
{
|
|
private readonly _2021_backend.Data.BackendContext _context;
|
|
|
|
public EditModel(_2021_backend.Data.BackendContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
[BindProperty]
|
|
public new User USER { get; set; }
|
|
private string _secret { get; set; }
|
|
|
|
public async Task<IActionResult> OnGetAsync(string? id)
|
|
{
|
|
|
|
if (id == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
int idx = int.Parse(id);
|
|
USER = _context.Users.Find(idx);
|
|
|
|
if (USER == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
_secret = USER.Secret;
|
|
USER.Secret = string.Empty;
|
|
return Page();
|
|
}
|
|
|
|
// To protect from overposting attacks, enable the specific properties you want to bind to, for
|
|
// more details, see https://aka.ms/RazorPagesCRUD.
|
|
public async Task<IActionResult> OnPostAsync()
|
|
{
|
|
if (!ModelState.IsValid)
|
|
{
|
|
return Page();
|
|
}
|
|
if (await _context.Users.AsNoTracking().Where(u => u.stuID == USER.stuID).CountAsync() > 0
|
|
&& (await _context.Users.AsNoTracking().Where(u => u.stuID == USER.stuID).FirstOrDefaultAsync()).Id != USER.Id
|
|
)
|
|
return new ConflictResult();
|
|
if (USER.Secret == null || USER.Secret == String.Empty)
|
|
{
|
|
var user = await _context.Users.AsNoTracking().Where(u => u.Id == USER.Id).FirstOrDefaultAsync();
|
|
user.Name = USER.Name;
|
|
user.stuID = USER.stuID;
|
|
user.isManager = USER.isManager;
|
|
_context.Attach(user).State = EntityState.Modified;
|
|
}
|
|
else
|
|
{
|
|
var user = await _context.Users.AsNoTracking().Where(u => u.Id == USER.Id).FirstOrDefaultAsync();
|
|
user.Name = USER.Name;
|
|
user.stuID = USER.stuID;
|
|
user.isManager = USER.isManager;
|
|
user.Secret = Utils.EvaCryptoHelper.Password2Secret(USER.Secret);
|
|
_context.Attach(user).State = EntityState.Modified;
|
|
}
|
|
|
|
|
|
try
|
|
{
|
|
await _context.SaveChangesAsync();
|
|
}
|
|
catch (DbUpdateConcurrencyException)
|
|
{
|
|
if (!UserExists(USER.Id))
|
|
{
|
|
return NotFound();
|
|
}
|
|
else
|
|
{
|
|
throw;
|
|
}
|
|
}
|
|
|
|
return RedirectToPage("./Index");
|
|
}
|
|
|
|
private bool UserExists(int id)
|
|
{
|
|
return _context.Users.Any(e => e.Id == id);
|
|
}
|
|
}
|
|
}
|