MVC中的验证规则和业务规则 [英] Validation Rules and Business Rules in MVC

查看:80
本文介绍了MVC中的验证规则和业务规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MVC Web项目.根据最佳实践,添加验证规则和业务规则的正确位置在哪里?

I have a MVC web project. According to best practice, where is the correct place to add my validation rules and business rules?

验证规则是必填字段和必填格式.

Validation rules would be the required fields and required formats.

业务规则为此电子邮件已在数据库中"

Business rules would be "this email is already taken in the database"

这是我目前在注册模型中进行的操作:

Here's how I am currently doing it in my register model:

public class RegisterModel : IValidatableObject
{
    [Display(Name = "Email address")]
    [Required(ErrorMessage = "The email address is required")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string Email { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var retVal = new List<ValidationResult>();
        using (var entity = new AcademicUniteDatabaseEntities())
        {
            if (entity.UserProfiles.Any(x => x.UserName == this.Email))
            {
                retVal.Add(new ValidationResult("Email already exist", new List<string> { "Email" }));
            }
        }

        return retVal;
    }
}

这是我的注册控制器:

    public ActionResult Register()
    {
        var model = new RegisterModel();
        return this.View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (!this.ModelState.IsValid)
        {
            return this.View(model);
        }

        model.CreateAccount();
        return this.View("WaitConfirmEmail");
    }

为什么我要这样做

  1. 当我在控制器中检查ModelState.IsValid时,它将检查电子邮件的格式以及数据库中是否已存在该电子邮件.我没有在控制器中对数据库进行任何调用,仅在模型中.(这是最佳做法吗?)
  2. 它还将电子邮件已存在"验证结果绑定到我的电子邮件"属性,因此我可以在视图上显示验证结果.

这是最佳做法吗?

  1. 这是在MVC中添加业务规则的正确方法吗?
  2. 为什么或为什么不呢?
  3. 如果这不是最佳实践,能否为我提供一个示例,说明如何最好地编程该注册模型来检查业务规则(如果已经存在电子邮件)?

推荐答案

一种选择是创建自定义验证器属性.使用您的解决方案,您可能会得到非常大的模型.另一种选择是创建可以插入控制器的静态帮助器.这里没有正确的答案,这只是您想要组织代码的方式.我的首选是将业务逻辑分布在您可以即插即用的自定义属性中.这样,您可以无缝重构.

One alternative is to create a custom validator attribute. With your solution, you could end up with very big models. Another alternative is to create static helpers that you can plug in the controller. There is no right answer here, it's just the way you'd like to organize code. My preference is to spread the business logic across custom attributes you can plug and play. This way you can refactor seamlessly.

这篇关于MVC中的验证规则和业务规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆