提问人:cruzz 提问时间:11/3/2023 最后编辑:marc_scruzz 更新时间:11/3/2023 访问量:113
ASP.NET Core 中的验证错误 - 该字段为必填项
Validation error in ASP.NET Core - the field is required
问:
我有一个正在研究的项目,它由一个小的 ASP.NET Core MVC 应用程序组成。
我遵循了课程,但是,视频中使用的版本是 2.1,我有 5,6,7。
该错误由 组成。问题是我的表单需要一个我在表单中没有的字段。我有一个字段,但它要求.ModelState.IsValid
create.cshtml
DepartmentId
Department
我的类和错误:
Seller.cs
:
using System.ComponentModel.DataAnnotations;
namespace LojaWebMvc.Models;
public class Seller
{
public int Id { get; set; }
[Required(ErrorMessage ="{0} required")]
[StringLength(60, MinimumLength = 3, ErrorMessage ="{0} size shold be between {2} and {1}")]
public string Name { get; set; }
[Required(ErrorMessage ="{0} required")]
[EmailAddress(ErrorMessage = "Enter a valid email")]
public string Email { get; set; }
[Display(Name="Birth Date")]
[DataType(DataType.Date)]
[Required(ErrorMessage ="{0} required")]
public DateTime BirthDate { get; set; }
[Display(Name = "Base Salary")]
[DisplayFormat(DataFormatString ="{0:F2}")]
[Required(ErrorMessage ="{0} required")]
[Range(100.0, 5000.0, ErrorMessage ="{0} must be from {1} to {2}")]
public double BaseSalary { get; set; }
public Department Department {get; set;}
public int DepartmentId { get; set; }
public ICollection<SalesRecord> Sales {get; set;} = new List<SalesRecord>();
public Seller()
{
}
public Seller(int id, string name, string email, DateTime birthdate, double salary, Department department)
{
Id = id;
Name = name;
Email = email;
BirthDate = birthdate;
BaseSalary = salary;
Department = department;
}
public void AddSales(SalesRecord sr)
{
Sales.Add(sr);
}
public void RemoveSales(SalesRecord sr)
{
Sales.Remove(sr);
}
public double TotalSales(DateTime initial, DateTime final)
{
return Sales.Where(sr => sr.Date >= initial && sr.Date <= final).Sum(sr => sr.Amount);
}
}
Department.cs
:
namespace LojaWebMvc.Models;
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Seller> Sellers { get; set; } = new List<Seller>();
public Department()
{
}
public Department(int id, string name)
{
Id = id;
Name = name;
}
public void AddSeller(Seller seller)
{
Sellers.Add(seller);
}
public double TotalSales(DateTime initial, DateTime final)
{
return Sellers.Sum(seller => seller.TotalSales(initial, final));
}
}
部门服务 :FindAll
...
public List<Department> FindAll()
{
//return _vsproContext.Department.OrderBy(x => x.Name).ToList();
var list = _vsproContext.Department;
var obj = new List<Department>();
obj = list.Select(x => new Department(
x.Id,
x.Name
)).ToList();
return obj;
}
...
SellerService
:
using LojaWebMvc.Models;
using LojaWebMvc.Services.Interfaces;
using LojaWebMvc.Data;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using LojaWebMvc.Services.Exceptions;
namespace LojaWebMvc.Services;
public class SellerService: ISellerService
{
private readonly VsproContext _vsproContext;
public SellerService(VsproContext vsproContext)
{
_vsproContext = vsproContext;
}
//
public List<Seller> FindAll()
{
// return _vsproContext.Seller.OrderBy(x => x.Name).ToList();
var list = _vsproContext.Seller;
var obj = list.Select(x => new Seller(x.Id, x.Name,
x.Email, x.BirthDate, x.BaseSalary, x.Department)).ToList();
return obj;
}
public Seller FindById(int id)
{
return _vsproContext.Seller.Include(obj => obj.Department).FirstOrDefault(x => x.Id == id);
// var obj = _vsproContext.Seller.Find(id);
// return obj;
}
public Seller Insert(Seller seller)
{
_vsproContext.Add(seller);
_vsproContext.SaveChanges();
return seller;
}
public void Remove(int id)
{
var obj = _vsproContext.Seller.Find(id);
_vsproContext.Remove(obj);
_vsproContext.SaveChanges();
}
public void Update(Seller seller)
{
if (!_vsproContext.Seller.Any(x => x.Id == seller.Id))
{
throw new NotFoundException("Error - Id not found");
}
try
{
_vsproContext.Update(seller);
_vsproContext.SaveChanges();
}
catch(DbUpdateConcurrencyException e)
{
throw new DbConcurrencyException(e.Message);
}
}
}
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Seller seller)
{
if (!ModelState.IsValid)
{
var message = string.Join(" | ", ModelState.Values
.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage));
System.Console.WriteLine(ModelState.Values);
var departments = _departmentService.FindAll();
var viewModel = new SellerFormViewModel{ Seller = seller, Departments = departments};
System.Console.WriteLine(message);
return View("Create", viewModel);
}
_sellerService.Insert(seller);
return RedirectToAction("Index");
}
如果您删除它,它可以正常工作,但是如果我尝试验证,它不会将其保存在数据库中,也不会返回任何错误。我被困住了。我使用得到错误输出if(!ModelState.Isvalid)...
System.Console.WriteLine(message)
错误:
“部门”字段为必填项。
答:
0赞
Qing Guo
11/3/2023
#1
您可以尝试将 Manully 添加到喜欢中:?
public Department? Department {get; set;}
或者:可以从项目文件中删除(双击项目名称或右键单击项目以选择“编辑项目文件”)。您可以阅读此内容以了解更多信息。<Nullable>enable</Nullable>
评论
0赞
cruzz
11/3/2023
哇。。!它的工作很好。非常感谢您的帮助,我已经尝试了 4 个小时,我的头已经很痛了。谢谢。
0赞
Qing Guo
11/3/2023
嗨@cruzz,不客气:),如果我的回答能帮助您解决问题,请您接受作为答案吗?参考:如何获取答案 非常感谢。
上一个:验证 pom.xml
下一个:ASP.NET 页面验证
评论