asp.net-mvc - .NET MVC 自定义验证(无数据注释)

标签 asp.net-mvc validation

使用 .NET MVC 和代码优先 EF 来实现请求的功能。业务对象比较复杂,我用的是System.ComponentModel.DataAnnotations.IValidatableObject验证业务对象。
现在我试图找到方法,如何显示来自业务对象的验证结果,使用 MVC ValidationSummary 而不使用数据注释。例如(非常简化):

业务对象:

    public class MyBusinessObject : BaseEntity, IValidatableObject
    {
        public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
           return Validate();
        }
        public IEnumerable<ValidationResult> Validate()
        {
           List<ValidationResult> results = new List<ValidationResult>();

           if (DealType == DealTypes.NotSet)
           {
                results.Add(new ValidationResult("BO.DealType.NotSet", new[] { "DealType" }));
           }

           return results.Count > 0 ? results.AsEnumerable() : null;
        }
    }

现在在我的 MVC Controller 中,我有这样的东西:
    public class MyController : Controller
    {
        [HttpPost]
        public ActionResult New(MyModel myModel)
        {
           MyBusinessObject bo = GetBoFromModel(myModel);
           IEnumerable<ValidationResult> result = bo.Validate();
           if(result == null)
           {
               //Save bo, using my services layer
               //return RedirectResult to success page
           }

           return View(myModel);
        }
    }

看来,我有Html.ValidationSummary(); .
我如何通过 IEnumerable<ValidationResult>到验证摘要?

我试图通过谷歌搜索找到答案,但我找到的所有示例都描述了如何使用模型中的数据注释而不是业务对象中的数据注释来显示验证摘要。

谢谢

最佳答案

在模型中添加属性,比如 BusinessError

在 View 中执行以下操作

  @Html.ValidationMessageFor(model => model.BusinessError)

然后在您的 Controller 中,每当您出现错误时,请执行以下操作
ModelState.AddModelError("BussinessError", your error)

关于asp.net-mvc - .NET MVC 自定义验证(无数据注释),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16066124/

相关文章:

asp.net - 使用 asp.net mvc 的 API 身份验证选项

asp.net-mvc - 有没有办法让 DefaultModelBinder 在绑定(bind)到 List<Enum> 时忽略空项

asp.net-mvc - ASP.NET MVC将表单值传递给操作方法

ruby-on-rails - RSpec/Shoulda : "should be_valid" fails, "contact.should be_valid"通过

xml - 如何使用 apache camel 验证 xsd?

asp.net-mvc - Autofac - 将属性注入(inject) asp.net mvc Controller

javascript - MVC - Html.Action 使用 Javascript 检索元素,然后将其作为参数传递给 Controller,然后返回 PartialView

c# - 如果在接口(interface)上定义属性,xVal 会起作用吗?

XML 验证错误 : EntityRef: expecting';'

javascript - 即使显示整个 TR,也会触发验证 :none