加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:42:10 所属栏目:asp.Net 来源:网络整理
导读:使用.NET MVC和代码优先EF来实现所请求的功能.业务对象相对复杂,我使用System.ComponentModel.DataAnnotations.IValidatableObject来验证业务对象. 现在我试图找到方法,如何使用MVC ValidationSummary显示业务对象的验证结果,而不使用数据注释.例如(非常简化
使用.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控制器中我有这样的事情:

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>到ValidationSummary?

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

谢谢

解决方法

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

在视图中执行以下操作

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

然后在您的控制器中出现错误时执行以下操作

ModelState.AddModelError("BussinessError",your error)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读