【问题标题】:ASP.NET MVC Validation Using qTip jQuery Plugin使用 qTip jQuery 插件的 ASP.NET MVC 验证
【发布时间】:2011-10-24 10:14:21
【问题描述】:

我正在使用找到的解决方案 here 使用 qTip jQuery 插件在工具提示中显示客户端验证错误。该解决方案非常适合客户端验证,但我希望能够以相同的方式显示服务器端验证错误。有谁知道如何使用 qTip 在工具提示中显示服务器端验证错误?

谢谢

【问题讨论】:

    标签: jquery asp.net-mvc asp.net-mvc-3 validation qtip


    【解决方案1】:

    如果存在服务器端验证错误,当页面加载时,将有一个带有“field-validation-error”类的 span 元素,因此我们可以简单地循环使用该类的所有元素,提取内容或错误消息,并将其显示在工具提示中。

    $(document).ready(function () {
        // Run this function for all validation error messages
        $('.field-validation-error').each(function () {
    
            // Get the name of the element the error message is intended for
            // Note: ASP.NET MVC replaces the '[', ']', and '.' characters with an
            // underscore but the data-valmsg-for value will have the original characters
            var inputElem = '#' + $(this).attr('data-valmsg-for').replace('.', '_').replace('[', '_').replace(']', '_');
    
            var corners = ['left center', 'right center'];
            var flipIt = $(inputElem).parents('span.right').length > 0;
    
            // Hide the default validation error
            $(this).addClass('Hidden');
    
            // Show the validation error using qTip
            $(inputElem).filter(':not(.valid)').qtip({                
                content: { text: $(this).text() } , // Set the content to be the error message
                position: {
                    my: corners[flipIt ? 0 : 1],
                    at: corners[flipIt ? 1 : 0],
                    viewport: $(window)
                },
                show: { ready: true },
                hide: false,                
                style: { classes: 'ui-tooltip-red' }
            });            
        });
    });
    

    这是一个blog post,它详细解释了如何执行此操作。

    【讨论】:

      【解决方案2】:

      Nick Olsen 发布的解决方案效果很好! 一项观察:

      此语句中使用的 .replace() 仅替换第一次出现的 ‘.’ ‘['']‘

      var inputElem = ‘#’ + $(this).attr(‘data-valmsg-for’).replace(‘.’, ‘_’).replace(‘[', '_').replace(']‘, ‘_’);
      

      要替换所有出现的行应该是这样的:

      var inputElem = "#" + $(this).attr("data-valmsg-for").replace(/\./g,"_").replace(/[\[\]]/g, "_");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-02
        • 1970-01-01
        • 2014-04-19
        • 2011-05-21
        • 2011-05-08
        • 2012-02-28
        • 2012-12-09
        • 1970-01-01
        相关资源
        最近更新 更多