您如何执行模型验证 [英] How do you perform model validation

查看:184
本文介绍了您如何执行模型验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我将实体框架用于SQL数据库,并希望在模型中执行客户端服务器验证.到目前为止,到目前为止还不错,但是当我添加部分类并尝试验证视图中的控件时,我发现Entity Framework(EF)已经向这些控件添加了验证并收到了编译错误. EF生成的客户端验证不如我所愿.

根据我的阅读,尽管可以,但您不应修改EF生成的内容.

所以我的问题是,如何在不修改EF代码的情况下添加其他验证?以前我没有对Partial类做很多工作,但是了解这些概念.

谢谢您,

Hi,

I''m using Entity Framework to a SQL database and would like to perform Client Side Server validation, within the Model. So far so good, however when I add my partial class and attempt to validate the controls in the view, I discover that Entity Framework (EF) has already added validation to these controls and receive a compile error. The EF generated the Client Side validation is not as strong as I would like.

From what I have read, although you can, you should not modify what EF generates.

So my question is how do you add additional validation without modifying the EF code? I have not done much work with Partial classes before, but understand the concepts.

Thank you,

推荐答案

我相信以下两篇文章将对您有所帮助:
http://www. asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs [ http ://robbincremers.me/2012/01/31/entity-framework-using-partial-classes-to-add-business-logic-and-validation-to-generated-entities/ [ ^ ]

它们向您展示了如何向生成的实体添加自己的附加验证.
I believe the following two articles will help you out:
http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs[^]

http://robbincremers.me/2012/01/31/entity-framework-using-partial-classes-to-add-business-logic-and-validation-to-generated-entities/[^]

They show you how to add your own additional validation to your generated entities.


个人而言,我不会将任何"Entity"对象传递回视图.我将创建一个视图模型",其中将仅包含呈现我的视图和客户端验证可以理解并为其创建适当规则的注释所需的数据.

您*可以*将注释添加到EF正在使用的POCO对象中,但这会破坏一些编程规则.在这种情况下,数据注释仅与视图"有关,因此不应放在我们的实体对象(通常是数据的表示形式)上

在创建"Internet"类型的项目时,Visual Studio自动创建的帐户"模型就是一个很好的例子,例如

Personally, I don''t pass any of the ''Entity'' objects back to the view. I would create a ''View Model'', which would contain just the data needed to present my View and annotations that the client side validation understands and creates approriate rules for.

You *can* add Annotations to your POCO objects that EF is using, however - this breaks a few programming rules. Data Annotations in this context are just about the ''View'' so shouldn''t be on our entity objects (which are generally a representation of data)

A good example of this is in the ''Account'' models that are automatically created by Visual Studio when you create an ''Internet'' type project, e.g.

public class ChangePasswordModel
{
    [Required]
    [DataType(DataType.Password)]
    [DisplayName("Current password")]
    public string OldPassword { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [DisplayName("New password")]
    [RegularExpression(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15}


",ErrorMessage = )] 公共 字符串 NewPassword { get ; 设置; } [DataType(DataType.Password)] [DisplayName(" )] [比较(" ,ErrorMessage = " 密码必须匹配")] 公共 字符串 ConfirmPassword { get ; 设置; } }
", ErrorMessage = "Password must contain at least one capital letter and one number")] public string NewPassword { get; set; } [DataType(DataType.Password)] [DisplayName("Confirm new password")] [Compare("NewPassword", ErrorMessage="Passwords must match")] public string ConfirmPassword { get; set; } }





@model ChangePasswordModel
@{
    ViewBag.Title = "Change Password";
}

<h2>Change Password</h2>
<p>
    Use the form below to change your password. 
</p>
<p>
    New passwords are required to be a minimum of @Membership.MinRequiredPasswordLength characters in length.
</p>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true, "Password change was unsuccessful. Please correct the errors and try again.")
    <div>
        <fieldset>
            <legend>Account Information</legend>

            <div class="editor-label">
                @Html.LabelFor(m => m.OldPassword)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.OldPassword)
                @Html.ValidationMessageFor(m => m.OldPassword)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.NewPassword)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.NewPassword)
                @Html.ValidationMessageFor(m => m.NewPassword)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.ConfirmPassword)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.ConfirmPassword)
                @Html.ValidationMessageFor(m => m.ConfirmPassword)
            </div>

            <p>
                <input type="submit" value="Change Password" />
            </p>
        </fieldset>
    </div>
}



在这种情况下,我们的视图绑定到我们的模型,该模型对任何数据或持久性一无所知.模型只知道它期望的字段,数据类型和验证规则.

控制器方法看起来像..



In this case, our View is bound to our model, which knows nothing about any data or persistence. All the Model knows is what fields it is expecting, data types and validation rules.

The controller method looks something like..

[HttpPost, Authorize]
public ActionResult ChangePassword(ChangePasswordModel model)
{
    if (ModelState.IsValid)
    {
        // ChangePassword will throw an exception rather than return false in certain failure scenarios.
        bool changePasswordSucceeded = this.MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);

        if (changePasswordSucceeded)
        {
            return RedirectToAction("ChangePasswordSuccess");
        }
        else
        {
            ModelState.AddModelError("", "Some Error Messge to Display.");
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}



关键是我们的视图将使用javascript(如果启用)针对我们的简单视图模型进行验证,控制器还将验证该模型,然后将从该视图收集的数据传递给其他服务,在这种情况下为"MembershipService" ''

我喜欢这种方法,因为关注点显然是分开的,并且每个组件都在执行应做的工作.



The key points are that our view will validate against our simple view model using javascript (if enabled) , the controller will also validate the model and then data collected from the view is passed on to some other Service, in this case the ''MembershipService''

I like this approach, since there is a clear seperation of concerns and every component is doing the job it''s supposed to do.


这篇关于您如何执行模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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