jQuery的MVC 4客户端验证无法工作 [英] Jquery MVC 4 Client side Validation Won't Work

查看:107
本文介绍了jQuery的MVC 4客户端验证无法工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用一个简单的MVC 4应用了jQuery验证插件 - 这是我在MVC 3,没有任何问题做的,但我不能让它工作在所有。

我要确认火时:

1 - 我的控制失去专注

2 - 上提交表单。

什么我已经错过了将AP preciated任何想法!

在_Layout.cshtml 脚本引用

 <  - 语言都:郎HTML  - >
< HEAD>
    <间的charset =UTF-8/>
    <标题> @ ViewBag.Title - AWC Web控制台< /标题>
    <链接HREF =〜/ favicon.ico的相对=快捷方式图标类型=图像/ X-图标/>
    < META NAME =视口CONTENT =WIDTH =设备宽度/>
    @ Styles.Render(〜/内容/ CSS)
    @ Scripts.Render(〜/包/ Modernizr的)
    <脚本的src =@ Url.Content(〜/脚本/ jQuery的-1.7.1.js)TYPE =文/ JavaScript的>< / SCRIPT>
    <脚本的src =@ Url.Content(〜/脚本/ jquery.validate.js)TYPE =文/ JavaScript的>< / SCRIPT>
    <脚本的src =@ Url.Content(〜/脚本/ jquery.validate.unobtrusive.js)TYPE =文/ JavaScript的>< / SCRIPT>< /头>

Index.cshtml标记与验证JS文件中的应用就绪功能
    

 <脚本类型=文/ JavaScript的>        $(文件)。就绪(函数(){        警报(DOC准备好了);        // JQuery的客户端验证
        $(#prodIdFilterForm)。验证(
            {
                onsubmit的:真实,
                规则:{
                    productId_str:{要求:真实,MINLENGTH个:10,编号:真正}
                },
                消息:{productId_str:产品ID必须输入},
                //当控制失去焦点小组审定
                onfocusout在:功能(元素){
                    警报(onfocusout在); //没有进入这个块!
                    $(#productId_str)removeAttr(风格)。
                    $(#productId_str)有效(); //火验证
                    $(元件).valid();
                }
                ,
                showErrors:功能(errorMap,errorList)
                {
                    如果(errorList.length大于0)
                    {
                        对于(VAR I = 0; I< errorList.length;我++)
                        {
                            $(#+ errorList [I] .element.id)的.css({'背景色':'#FFDFDF'});
                        }
                    }
                }
            }
            );    }); // DocReady< / SCRIPT>

组成标记车身
     

@ {
     ViewBag.Title =消息;
     布局=〜/查看/共享/ _Layout.cshtml
}
@using(Html.BeginForm(SelectProduct,WMSMessages,模型,FormMethod.Post,新{@id =prodIdFilterForm}))
{
   <字段集类=过滤>
      <传奇> SelectExtensions产品< /传说>
      < D​​IV>
         < B>产品编号:LT; / B>
         @ Html.TextBoxFor(型号=> model.productId_str,新{@id =productId_str})         < D​​IV CLASS =filterSubmitBox>
            <输入类型=提交值=显示消息/>
         < / DIV>
      < / DIV>
   < /字段集>
}


解决方案

有关客户端validataion微软使用jquery.validate.unobtrusive.js文件。
<一href=\"http://www.asp.net/mvc/tutorials/older-versions/javascript/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript\">Client端验证asp.net mvc的


  

启用客户端验证


  
  

要启用客户端验证在ASP.NET MVC 3,你必须设置两个
  标志并且必须包括3 JavaScript文件。


  
  

打开应用程序的Web.config文件。确认
  ClientValidationEnabled和UnobtrusiveJavaScriptEnabled被设置为
  真正的应用程序设置。从根下面的片段
  Web.config文件中显示了正确的设置:


 &LT;&的appSettings GT;
  &LT;添加键=ClientValidationEnabledVALUE =真/&GT;
  &LT;添加键=UnobtrusiveJavaScriptEnabledVALUE =真/&GT;
 &LT; /的appSettings&GT;

设置UnobtrusiveJavaScriptEnabled为true使不显眼的Ajax和不显眼的客户端验证。当您使用不引人注目的验证,验证规则都变成HTML5属性。 HTML5属性名称只能包含小写字母,数字和破折号

例如,如果你说需要attribue电子邮件和与它的错误信息。它将数据的属性附加到这样的元素。

 &LT;输入数据-VAL =真
        数据-VAL-所需=电子邮件是必需的(我们承诺不垃圾邮件!)。
        ID =电子邮件NAME =电子邮件类型=文本值=/&GT;

设置ClientValidationEnabled为true,使客户端验证。通过在应用程序Web.config文件中设置这些键,您可以启用为整个应用程序客户端验证和不显眼的JavaScript。您还可以启用或使用以下code禁用个人意见或控制器方法这些设置:

了解更多信息:


  1. Asp.net MVC验证

  2. MVC客户端验证

I'm trying to use the jQuery validation plugin on a simple MVC 4 application - something I've done in MVC 3 with no problems, but I can't get it working at all.

I want the validation to fire when:

1 - my control looses focus .

2- on form submit.

Any ideas on what I've missed would be appreciated !

Script references in _Layout.cshtml

<!-- language-all: lang-html -->
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title - AWC Web Console</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

</head>

Index.cshtml markup with validation JS applied in Doc ready function

    <script type="text/javascript">

        $(document).ready(function () {

        alert("doc ready");

        // JQuery client validation
        $("#prodIdFilterForm").validate(
            {
                onsubmit: true,
                rules: {
                    productId_str: {required: true, minlength: 10, number:true }
                },
                messages: { productId_str: "product Id must be entered" },
                // Force validation when control looses focus 
                onfocusout: function (element) {
                    alert("onfocusout");   // not entering this block !
                    $("#productId_str").removeAttr('style');
                    $("#productId_str").valid();   // fire validation
                    $(element).valid();
                }
                ,
                showErrors: function (errorMap, errorList)
                {
                    if (errorList.length > 0)
                    {
                        for (var i = 0; i < errorList.length; i++)
                        {
                            $("#" + errorList[i].element.id).css({ 'background-color': '#FFDFDF' });
                        }
                    }
                }
            }   
            );

    });  // DocReady

</script>

Body of form markup

@{
     ViewBag.Title = "Messages";
     Layout = "~/Views/Shared/_Layout.cshtml";
}


@using ( Html.BeginForm("SelectProduct", "WMSMessages", Model, FormMethod.Post, new {  @id = "prodIdFilterForm"} ) )
{
   <fieldset class="filtering">
      <legend>SelectExtensions Product</legend>
      <div>
         <b>Product Id:</b>
         @Html.TextBoxFor(model => model.productId_str, new { @id ="productId_str"}  )

         <div class="filterSubmitBox">
            <input type="submit" value="Show Messages" />
         </div>   
      </div>
   </fieldset>
}

解决方案

For client side validataion microsoft uses jquery.validate.unobtrusive.js file. Client side validation asp.net mvc

Enabling Client-Side Validation

To enable client-side validation in ASP.NET MVC 3, you must set two flags and you must include three JavaScript files.

Open the application's Web.config file. Verify that ClientValidationEnabled and UnobtrusiveJavaScriptEnabled are set to true in the application settings. The following fragment from the root Web.config file shows the correct settings:

 <appSettings>
  <add key="ClientValidationEnabled" value="true"/> 
  <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 
 </appSettings>

Setting UnobtrusiveJavaScriptEnabled to true enables unobtrusive Ajax and unobtrusive client validation. When you use unobtrusive validation, the validation rules are turned into HTML5 attributes. HTML5 attribute names can consist of only lowercase letters, numbers, and dashes

for example if you said required attribue for email and with its error message. it will append data-attributes to element like this.

 <input data-val="true"
        data-val-required="Email is required (we promise not to spam you!)."
        id="Email" name="Email" type="text" value="" />

Setting ClientValidationEnabled to true enables client-side validation. By setting these keys in the application Web.config file, you enable client validation and unobtrusive JavaScript for the entire application. You can also enable or disable these settings in individual views or in controller methods using the following code:

for more info :

  1. Asp.net MVC validation
  2. MVC client side validation

这篇关于jQuery的MVC 4客户端验证无法工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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