最佳实践验证视图模型在ASP.NET MVC [英] Best Practices ViewModel Validation in ASP.NET MVC

查看:182
本文介绍了最佳实践验证视图模型在ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 DataAnnotations 来验证我的视图模型 jquery.validate客户端.unobtrusive 和服务器端的 ASP.NET MVC 应用程序。

就在不久以前,我想通了,我可以写这样的验证:

  [必需(的ErrorMessage ={0}要求)]
公共字符串名称{;组; }

这样我可以很容易地定义在一些普通字符串的配置或资源,并始终用它,在 DataAnnotations 。所以它会更容易改变我的未来在整个应用程序验证消息。

我也知道,有一个 FluentValidation 库,允许添加验证规则已经存在的视图模型。我知道,有一个与添加/编辑的ViewModels ,可能有类似的领域,但不同ValidationRules一个问题。

这是来自客户端验证的另一个问题是HTML新增为 DOM (使用 Ajax请求)应该解释为允许验证。这就是我如何做到这一点:

  $('#一些Ajax的形式')的数据('验证',NULL);
$ .validator.unobtrusive.parse('#一些Ajax的形式');

所以我有一些问题:


  1. 有一些其他有用的做法,可以帮助集中所有的验证规则应用?

  2. 什么是解决添加/编辑视图模型验证问题最好的办法?我可以用 DataAnnotations FluentValidation 或单独添加和编辑的ViewModels 仍然是一个最好的选择?

  3. 有没有什么更好的方法来初始化新的 DOM Ajax调用等元素收到的验证,我提?

编辑:

我不问如何创建自己的 DataValidators 我知道如何做到这一点。我寻找的方式如何更高效和易于维护的方式使用它们。


解决方案

要回答你的问题3TH第一:没有没有那么没有更简单的方法,你在做什么。 code两行得到它的工作难言轻松。虽然有一个插件,您可以使用,就像在这个问题不显眼的审定与动态内容

您的第一个问题,如何集中验证,我通常使用一个单独的类文件来存储我所有的验证规则。这样,我就不必通过浏览每一个类文件,找到规则,但让他们都在同一个地方。如果是这样的好,是选择的问题。我开始使用它的主要原因,是为了能够验证添加到自动生成的类,就像从实体框架类。

所以我有 ModelValidation.cs 在我的数据层称为文件,并有code为我所有的车型,如

  ///<总结>
///用于在&lt验证规则;见CREF =测试/>目的
///< /总结>
///<&言论GT;
/// 2015年1月26日:创建
///< /言论>
[MetadataType(typeof运算(TestValidation))]
公共部分类测试{}
公共类TestValidation
{
    ///<总结>名称是必需的< /总结>
    [需要]
    [StringLength(100)]
    公共字符串名称{;组; }    ///<总结>文本多行< /总结>
    [数据类型(DataType.MultilineText)
    [AllowHtml]
    公共字符串文本{搞定;组; }
}

现在,你注意到了我没有提供实际的错误信息。我使用<一个href=\"http://haacked.com/archive/2011/07/14/model-metadata-and-validation-localization-using-conventions.aspx/\"相对=nofollow>由Haacked约定来添加消息。它可以很方便地增加本地化的验证规则。

这基本上可以归结为含有点像林资源文件:

  TEST_NAME =提供的名字
Test_Name_Required =名称是必需的

当你骂经常这些消息并命名将用于 MVC视图 code像

 &LT; D​​IV CLASS =编辑容器&GT;
    &LT; D​​IV CLASS =编辑标记&GT;
        @ Html.LabelFor(型号=&GT; model.Name)LT; - !提供的名字 - &GT;
    &LT; / DIV&GT;
    &LT; D​​IV CLASS =主编场&GT;
        @ Html.EditorFor(型号=&GT; model.Name)
        @ Html.ValidationMessageFor(型号=&GT; model.Name)LT;! - 姓名是必需的 - &GT;
    &LT; / DIV&GT;
&LT; / DIV&GT;

您的第二个问题,对于添加/编辑了解不同的验证可以通过两种方式来处理。最好的办法,是使用的意见,他们实际上意。这意味着你不通过你的实际模型的观点,但你只创建一个包含数据的视图模式。所以,你有一个视图 通过适当的验证规则修改模型创建和视图模型与适当的规则,当他们通过你在你的实际模型插入的结果。
然而,这需要更多的code和体力劳动,所以我可以想像你不是真的愿意去做这样的。

另一种选择是使用条件验证像viperguynaz解释。现在不是一个布尔值,我的课,需要编辑之间的变化/加有一个主键 编号 INT 。所以我检查编号方式&gt; 0 来确定它是否是一个编辑与否

更新:

如果你想在每一个Ajax调用更新验证,你可以使用 jQuery的ajaxComplete 。这将每一个Ajax请求后重新验证所有形式。

 的$(document).ajaxComplete(函数(){
    $('形式')。每个(函数(){
        变量$ EL = $(本);
        $ el.data('验证',NULL);
        $ .validator.unobtrusive.parse($ EL);
    })
});

如果这是你想要的东西,就看你怎么经常收到通过 AJAX 的形式。如果你有很多的 AJAX 的要求,如轮询状态每10秒,比你不想要这个。如果你有一个偶然的 AJAX 请求时,大多含有一种形式,那么你可以使用它。

如果你的 AJAX 返回要验证一个表单,那么是的,这是很好的做法,更新验证。但我想一个更好的问题是我是否真的需要通过AJAX发送的形式?
AJAX 是有趣和有用的,但它应该与良苦用心使用。

I am using DataAnnotations to validate my ViewModel on client side with jquery.validate.unobtrusive and on server side in ASP.NET MVC application.

Not so long time ago, I figured out that I can write validation like this:

[Required(ErrorMessage = "{0} is required")]
public string Name { get; set; }

That way I can easily define some general strings in config or in resources and always use it in DataAnnotations. So it will be easier to change validation messages in my whole application in future.

Also I know that there is a FluentValidation library that allows to add validation rules to already existing ViewModel. I know that there is a problem with Add/Edit ViewModels that could have similar fields but different ValidationRules.

Another problem that comes from client validation is that html newly added to DOM (using ajax request) should be parsed to enable validation. This is how I do it:

$('#some-ajax-form').data('validator', null); 
$.validator.unobtrusive.parse('#some-ajax-form');

So I have some questions:

  1. Is there some other useful practises that could help centralize all validation rules in application?
  2. What's is a best way to solve Add/Edit ViewModel Validation problem? Can I use DataAnnotations with FluentValidation or separate Add and Edit ViewModels still is a best option?
  3. Is there any better way to initialize validation on new DOM elements that received with ajax call other that I mention?

EDIT:

I'm not asking how to create my own DataValidators I know how to do it. I seeking of ways how to use them in more productive and easy maintainable way.

解决方案

To answer your 3th question first: No there is no easier way then what you are doing. Two lines of code to get it working can hardly be easier. Although there is a plug-in you could use, like explained in the question unobtrusive validation not working with dynamic content

Your first question, how to centralize validation, I normally use a separate class file to store all my validation rules. This way I don't have to browse through every single class file to find the rules, but have them all in one place. If that's better, is matter of choice. The main reason I started to use it, is to be able to add validation to auto-generated classes, like classes from the Entity Framework.

So I have a file called ModelValidation.cs in my data layer, and have code for all my models like

/// <summary>
/// Validation rules for the <see cref="Test"/> object
/// </summary>
/// <remarks>
/// 2015-01-26: Created
/// </remarks>
[MetadataType(typeof(TestValidation))]
public partial class Test { }
public class TestValidation
{
    /// <summary>Name is required</summary>
    [Required]
    [StringLength(100)]
    public string Name { get; set; }

    /// <summary>Text is multiline</summary>
    [DataType(DataType.MultilineText)]
    [AllowHtml]
    public string Text { get; set; }
}

Now as you noticed I don't provide the actual error message. I use conventions by Haacked to add the messages. It makes it simple to add localized validation rules.

It basically comes down to a recource file containing something like:

Test_Name = "Provide name"
Test_Name_Required = "Name is required"

And these messages and naming will be used when you call regular MVC view code like

<div class="editor-container">
    <div class="editor-label">
        @Html.LabelFor(model => model.Name) <!--"Provide name"-->
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name) <!--"Name is required"-->
    </div>
</div>

Your second question, about different validation for add/edit can be handled in two ways. The best way, would be to use views as they are actually intended. That means you don't pass your actual models to the views, but you create a view model that contains only the data. So you have a view model for Create with the proper validation rules and a view model for Edit with the proper rules, and when they pass you insert the result in your actual model. This however requires a lot more code and manual work, so I can imagine you're not really willing to do it like this.

Another option would be to use conditional validation like explained by viperguynaz. Now instead of a boolean, my classes that require a change between edit/add have a primary key Id int. So I check if Id>0 to determine if it is an edit or not.

UPDATE:

If you want to update validation on every ajax call, you could use jQuery ajaxComplete. This will revalidate all forms after every ajax request.

$( document ).ajaxComplete(function() {
    $('form').each(function() {
        var $el = $(this);
        $el.data('validator', null); 
        $.validator.unobtrusive.parse($el);
    })
});

If this is something you want, depends on how often you receive a form via AJAX. If you have a lot of AJAX request, like polling a status every 10seconds, than you don't want this. If you have an occasional AJAX request, that mostly contains a form, then you could use it.

If your AJAX returns a form you want to validate, then yes, it is good practise to update the validation. But I guess a better question would be "Do I really need to send the form by AJAX?" AJAX is fun and useful, but it should be used with care and thought.

这篇关于最佳实践验证视图模型在ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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