【问题标题】:Is it possible to change ModelStateError on a specific object in list?是否可以在列表中的特定对象上更改 ModelStateError?
【发布时间】:2021-11-11 16:43:52
【问题描述】:

我有一个 httpPost,我想在其中循环浏览汽车列表。汽车有一些属性已经过验证,如果汽车是deleted,则对象上的布尔值设置为true。

我现在想清除已删除 bool 的汽车上的 modelState。我正在寻找类似的东西:

foreach (var c in cars ) { 
   if(c.IsDeleted) {
      // delete all the errors for this specific car
      ...
   }
} 

有什么办法吗?

【问题讨论】:

    标签: c# asp.net-core razor


    【解决方案1】:

    你可以尝试得到一个IsDeleted为真的没有汽车的列表,然后使用TryValidateModel检查新的列表,这样你将得到一个没有汽车错误的ModelState,IsDeleted为真,并且您无需逐个列表并删除有关它的错误。这是一个演示:

    型号:

    public class Cars
        {
            public List<Car> CarList { get; set; }
        }
        public class Car
        {
            [Required]
            public string Id { get; set; }
            [Required]
            public string Name { get; set; }
            public bool IsDeleted { get; set; }
        }
    

    代码:

    public IActionResult Index(Cars cars)
            {
                
                List<Car> list = cars.CarList.Where(c => c.IsDeleted != true).ToList();
                Cars newCars = new Cars { CarList = list };
                ModelState.Clear();
                TryValidateModel(newCars);
                //after `TryValidateModel` you will get a ModelState without errors of cars which `IsDeleted` is true
               
                return View();
            }
    

    【讨论】:

      猜你喜欢
      • 2014-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2021-10-31
      • 1970-01-01
      • 2018-07-26
      相关资源
      最近更新 更多