如何在下拉列表上设置验证消息?

时间:2019-07-30 05:16:46

标签: asp.net-mvc validation .net-core

这是问题所在。我的SalesCenterId的{​​{1}}属性上方有一个[Range]属性。从我的角度来看,我有一个带有默认选项“ --- Select ---”的下拉列表,以及一些具有不同ID的销售中心。例如,如果我将范围设置在0到1之间,那么当选择ID = 2的销售中心时,我的自定义错误消息会起作用。但是,当我选择默认选项“ --- Select ---”(id = 0,范围在1到1000之间)时,将显示默认错误消息:“值'--- Select ---'无效ViewModel。”为什么是这样?我检查了调试过程,发现选择“ --- Select ---” Id = 0时。

我正在使用MVC core 2.2

ViewModel:

SalesCenterId

验证消息范围:

public class OrderViewModel
    {
        [Required(ErrorMessage = "*The Last Name field is required.")]
        public string LastName { get; set; }
        [Required(ErrorMessage = "*The First Name field is required.")]
        public string FirstName { get; set; }
        [Required(ErrorMessage = "*The Middle Name field is required.")]
        public string MiddleName { get; set; }
        [Required(ErrorMessage = "*The Pin field is required.")]
        public string Pin { get; set; }
        [Required(ErrorMessage = "*The Phone field is required.")]
        public string Phone { get; set; }
        [Required(ErrorMessage = "*The Email field is required.")]
        public string Email { get; set; }
        [Required(ErrorMessage = "*The Serial Number field is required.")]
        public string SerialNumber { get; set; }

        [Range(1, 1000, ErrorMessage="jgsjfdngi")]
        public int SalesCenterId { get; set; }

        [Range(1, 999, ErrorMessage = "jgsjfdngi")]
        public int OrderTimeId { get; set; }

        [JsonIgnore]
        [IgnoreDataMember]
        public SalesCenter SalesCenter { get; set; }

        public List<CartItem> Cart { get; set; }

        public OrderTime OrderTime { get; set; }

        public decimal TotalPrice { get; set; }
    }

选择列表:

<p><span asp-validation-for="SalesCenterId" class="error"></span></p>

我希望输出为“ jgsjfdngi”,但实际输出为“值'--- Select ---'对SalesCenterId无效。”

1 个答案:

答案 0 :(得分:0)

您是否在控制器中使用过ModelState.IsValid? 试试这个

if (ModelState.IsValid)  
 {  
  // your code  
  return View();  
 }  
 return View();