- 在ViewModel中使用Annotations进行验证:
public class MyViewModel
{
[Range(1, 100, ErrorMessage = "Age must be between 1 and 100")]
public int Age { get; set; }
}
- 使用ModelState.IsValid属性进行验证:
[HttpPost]
public IActionResult MyAction(MyViewModel model)
{
if (ModelState.IsValid)
{
//If the Model state is valid, do something
}
else
{
return View(model);
}
}
- 自定义错误信息:
services.AddMvc()
.AddMvcOptions(options => options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(
() => "The field is required"));
- 重新定义数字字段数据类型:
[Range(typeof(decimal), "0", "99.99")]
public decimal Age { get; set; }