【问题标题】:ASP.NET MVC 2 List<T> model validationASP.NET MVC 2 List<T> 模型验证
【发布时间】:2013-01-07 15:59:30
【问题描述】:

我正在开发 MVC 2 应用程序,但遇到了问题。我的代码如下所示:

public ActionResult Users()
        {
            try
            {
                var model = new List<User>
                                {
                                    new User
                                        {
                                            Name = "Test",
                                            UserID = 1,
                                            Salary = 1000m
                                        }
                                };
                return View(model);
            }
            catch (Exception ex)
            {
                //Log exception
                return View("ErrorPage");
            }
        }

        [HttpPost]
        public ActionResult Users(IEnumerable<User> users)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    return RedirectToAction("Index");
                }

                return View(users);
            }
            catch (Exception ex)
            {
                //Log exception
                return View("ErrorPage");
            }
        }

和类用户

public class User
    {
        [Required]
        public string Name{ get; set; }

        [Required]
        public int UserID{ get; set; }

        [Required]
        public decimal Salary{ get; set; }
    }

我想创建自定义属性 (DataAnnototation) 来验证 IEnumerable 用户在发布表单时的工资总和是否小于 10000?我可以在这里做吗,因为我的模型是 List?

【问题讨论】:

  • 不要吞下异常

标签: .net validation asp.net-mvc-2 data-annotations asp.net-mvc-validation


【解决方案1】:

数据注释不能跨集合操作。

相反,您需要在操作中手动验证。

然后您可以拨打ModelState.AddModelError()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    相关资源
    最近更新 更多