我正在开发一个剃刀页面项目。我有一个员工模型,它具有字节数组类型的图片属性。尽管当我检查
modelstate.isvalid
时,图片被分配了字节数组,但emp.picture
无效,这里是我的员工模型和相关代码:
public class Employee
{
public int Id { get; set; }
[Required(ErrorMessage = "Please enter first name")]
[DisplayName("First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter last name")]
[DisplayName("Last Name")]
public string LastName { get; set; }
[Required(ErrorMessage = "Please enter age")]
[Range(20, 60, ErrorMessage = "Valid age is between 20 to 60")]
public int Age { get; set; }
[Required(ErrorMessage = "Please select joining date")]
[DisplayName("Joining Date")]
[DataType(DataType.Date)]
public DateTime JoiningDate { get; set; }
[Required(ErrorMessage = "Please enter email address")]
[EmailAddress]
public string Email { get; set; }
[Required(ErrorMessage = "Please enter phone number")]
[DisplayName ("Phone No")]
[Phone]
public string PhoneNo { get; set; }
public byte[] Picture { get; set; }
public bool Gender { get; set; }
public bool Active { get; set; } = true;
[Required(ErrorMessage = "Please select a Department")]
public int DepartmentId { get; set; }
public Department? Department { get; set; }
[NotMapped]
public IFormFile ImageFile { get; set; }
}
public async Task<IActionResult> OnPostAsync()
{
byte[] bytes;
if (emp.ImageFile != null)
{
using (Stream fs = emp.ImageFile.OpenReadStream())
{
using (BinaryReader br = new BinaryReader(fs))
{
bytes = br.ReadBytes((Int32)fs.Length);
}
}
emp.Picture = bytes;
}
if (!ModelState.IsValid)
{
return Page();
}
_db.Employees.Add(emp);
await _db.SaveChangesAsync();
TempData["Success"] = "Employee created successfully....";
return RedirectToPage("/Employees/Index");
}
}
我期望该图片应该具有价值,但我不知道为什么没有。
模型绑定发生在
OnPostAsync
方法中的代码执行之前,并且 ModelState
不会因您向 Picture
属性赋值而更新。 当您很高兴为 ModelState.Remove
分配了值后,可以使用 Picture
方法删除无效条目:
public async Task<IActionResult> OnPostAsync()
{
byte[] bytes;
if (emp.ImageFile != null)
{
using (Stream fs = emp.ImageFile.OpenReadStream())
{
using (BinaryReader br = new BinaryReader(fs))
{
bytes = br.ReadBytes((Int32)fs.Length);
}
}
emp.Picture = bytes;
ModelState.Remove("emp.Picture");
}
if (!ModelState.IsValid)
{
return Page();
}
_db.Employees.Add(emp);
await _db.SaveChangesAsync();
TempData["Success"] = "Employee created successfully....";
return RedirectToPage("/Employees/Index");
}