ASP.Net MVC:您可以通过 AJAX / jQuery 调用使用数据注释/验证吗?

发布于 2024-11-03 19:39:53 字数 228 浏览 2 评论 0 原文

您可以通过 AJAX / jQuery 调用使用数据注释/验证吗?如果是这样,请提供一个示例或显示示例的帖子。

基本上我已经看到了如何使用数据注释的示例,但是它带有完整的回发。有没有办法处理 AJAX / jQuery 调用?不确定您将如何执行此操作,因为我不确定您将如何在客户端构建模型对象。 (我认为这是你必须做的。)

有人告诉我这是可以做到的,但我只是不明白这是怎么回事。

感谢您的帮助。

Can you use Data Annotations / Validation with an AJAX / jQuery call? If so, please provide an example or a post which shows an example.

Basically I have seen an example of how to use Data Annotations, however it was with a full post back. Is there a way to do with an AJAX / jQuery call? Not sure how you would do this since I am not sure how you would construct the Model object on the client side. (I assume this is what you would have to do.)

Someone told me this can be done, but I just don't understand how it can be.

Thanks for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

∞琼窗梦回ˉ 2024-11-10 19:39:53

是的 - 100% 我一直这样做。使用 Ajax.BeginForm 并使用不显眼的验证
http://completedevelopment.blogspot.com/2011 /02/unobstrusive-javascript-in-mvc-3-helps.html

这将发出客户端所需的所有内容..尽管您必须再次连接验证器来告诉 jQuery我们已经加载了一些需要验证的内容

我相信我从以下位置得到了这个想法/代码: http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/

不管怎样,我下面的内容都有效,而且我目前正在使用它,尽管我添加了一些调试。

(function ($) {
    $.validator.unobtrusive.parseDynamicContent = function (selector) {

        var len = $(selector).length;

        //alert('got length');
        if ($(selector).length == 0) {
            alert('The selector (usually a div) passed in as the root level to start validation parsing at (rather than parsing the whole document again) could not be found in the DOM. Validation on this form will not likely continue. The selector parameter is:' + selector);
            return;
        }
        //use the normal unobstrusive.parse method
        $.validator.unobtrusive.parse(selector);

        //get the relevant form
        var form = $(selector).first().closest('form');
        if (form.length == 0) {
            alert('Could not find a form that was a parent of selector:' + selector + '\nValidation may not work properly');
            return;
        }


        //get the collections of unobstrusive validators, and jquery validators
        //and compare the two
        var unobtrusiveValidation = form.data('unobtrusiveValidation');
        //alert(unobtrusiveValidation.length);
        var validator = form.validate();

        $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
            if (validator.settings.rules[elname] == undefined) {
                var args = {};
                $.extend(args, elrules);
                args.messages = unobtrusiveValidation.options.messages[elname];
                //$('[name=' + elname + ']').rules("add", args);
                $('[name="' + elname + '"]').rules("add", args);
            } else {
                $.each(elrules, function (rulename, data) {
                    if (validator.settings.rules[elname][rulename] == undefined) {
                        var args = {};
                        args[rulename] = data;
                        args.messages = unobtrusiveValidation.options.messages[elname][rulename];

                        $('[name="' + elname + '"]').rules("add", args);
                    }
                });
            }
        });

    }
})($);

然后在使用 ajax 加载的每个部分视图(或页面)中,包含以下内容:
(注意 editCustomerAddress 是包含我的新内容的 div 名称,因此 jQuery 不必重新解析我页面上的所有内容,而只需从我的动态内容开始)

  <script type="text/javascript">
        try {
            //Since this may have been loaded as dynamic content ensure jQuery client validation knows we should be validating the content in this view.
            //jQuery validation runs when the original page loads - on the original content and not on dynamic (in this case ajax) content.
            //We don't need to validate the whole form again, only from this div down.

            //if I have a problem in jQuery 5, then try: $.validator.unobtrusive.parse("#editZone > div > form"); 
            $.validator.unobtrusive.parseDynamicContent('#editCustomerAddress');
        }
        catch (err) {
            alert('An error occured trying to tell jQuery to validate our new content. Ensure the code for parseDynamicContent has been included and you are referencing a valid element. Also, ensure the form has a context if it is a partial view by calling if (ViewContext.FormContext == null){ViewContext.FormContext = new FormContext();}  If that code is not present, data-val-* attributes will not be rendered.\n' + err);
        }

    </script>

此外 - 您希望确保您的部分视图不没有自己的 ajax 或 html 表单,您需要通过

@{ 拥有表单上下文
if(ViewContext.FormContext == null) {ViewContext.FormContext = new FormContext();
否则

,辅助方法将不会发出您的 data-val-* 属性。如果您的视图没有 Ajax.BeginForm 或 Html.BeginForm 来创建自己的表单上下文,则需要这个。

Yes - 100% I do it all the time. Use Ajax.BeginForm and use unobtrusive validation
http://completedevelopment.blogspot.com/2011/02/unobstrusive-javascript-in-mvc-3-helps.html

this will emit everything you need client side.. although you have to hook up the validators again to tell jQuery that we have loaded some content that it will need to validate

I believe I got this idea/code from: http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/

either way what I have below works and I'm currently using it although I added a little debugging to it.

(function ($) {
    $.validator.unobtrusive.parseDynamicContent = function (selector) {

        var len = $(selector).length;

        //alert('got length');
        if ($(selector).length == 0) {
            alert('The selector (usually a div) passed in as the root level to start validation parsing at (rather than parsing the whole document again) could not be found in the DOM. Validation on this form will not likely continue. The selector parameter is:' + selector);
            return;
        }
        //use the normal unobstrusive.parse method
        $.validator.unobtrusive.parse(selector);

        //get the relevant form
        var form = $(selector).first().closest('form');
        if (form.length == 0) {
            alert('Could not find a form that was a parent of selector:' + selector + '\nValidation may not work properly');
            return;
        }


        //get the collections of unobstrusive validators, and jquery validators
        //and compare the two
        var unobtrusiveValidation = form.data('unobtrusiveValidation');
        //alert(unobtrusiveValidation.length);
        var validator = form.validate();

        $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
            if (validator.settings.rules[elname] == undefined) {
                var args = {};
                $.extend(args, elrules);
                args.messages = unobtrusiveValidation.options.messages[elname];
                //$('[name=' + elname + ']').rules("add", args);
                $('[name="' + elname + '"]').rules("add", args);
            } else {
                $.each(elrules, function (rulename, data) {
                    if (validator.settings.rules[elname][rulename] == undefined) {
                        var args = {};
                        args[rulename] = data;
                        args.messages = unobtrusiveValidation.options.messages[elname][rulename];

                        $('[name="' + elname + '"]').rules("add", args);
                    }
                });
            }
        });

    }
})($);

then in each partial view (or page) that you use ajax to load, have this:
(note editCustomerAddress is the div name that contains my new content, so jQuery doesnt have to reparse everything on my page but only from my dynamic content down)

  <script type="text/javascript">
        try {
            //Since this may have been loaded as dynamic content ensure jQuery client validation knows we should be validating the content in this view.
            //jQuery validation runs when the original page loads - on the original content and not on dynamic (in this case ajax) content.
            //We don't need to validate the whole form again, only from this div down.

            //if I have a problem in jQuery 5, then try: $.validator.unobtrusive.parse("#editZone > div > form"); 
            $.validator.unobtrusive.parseDynamicContent('#editCustomerAddress');
        }
        catch (err) {
            alert('An error occured trying to tell jQuery to validate our new content. Ensure the code for parseDynamicContent has been included and you are referencing a valid element. Also, ensure the form has a context if it is a partial view by calling if (ViewContext.FormContext == null){ViewContext.FormContext = new FormContext();}  If that code is not present, data-val-* attributes will not be rendered.\n' + err);
        }

    </script>

Also - you want to make sure your partial views that don't have their own ajax or html forms you need to have a form context via

@{
if(ViewContext.FormContext == null) {ViewContext.FormContext = new FormContext();
}

otherwise your data-val-* attributes will not be emitted by the helper methods. You need this if your views do not have an Ajax.BeginForm or Html.BeginForm to create their own form context.

且行且努力 2024-11-10 19:39:53

如果您使用 Html.AjaxForm(而不是 Html.BeginForm),那么它将使用 Ajax 进行验证。

但是我不认为你可以使用 jQuery 进行验证。 Microsoft 有自己的 Ajax 库,他们自己调用/维护它。我不认为你可以在两者之间挂钩你自己的代码。

If you use Html.AjaxForm (instead of Html.BeginForm) then it will validate using Ajax.

However I don't think you can validate using jQuery. Microsoft has it's own Ajax libraries and they call/maintain it themselves. I don't think you can hook your own code in between.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文