在MVC3上进行验证有很多麻烦.当我直接加载页面时,它工作正常,但是当我使用
jquery AJAX POST时它不会验证:
这个表单使用$(‘#modal-dialog’)加载.load(‘/ DartsMVC / Restaurant / Edit / 13’),这是渲染的HTML:
<form action="/DartsMVC/Restaurant/Edit/13" method="post"> <fieldset> <legend>Restaurant</legend> <input data-val="true" data-val-number="The field RestaurantID must be a number." data-val-required="The RestaurantID field is required." id="RestaurantID" name="RestaurantID" type="hidden" value="13"> <div class="editor-label"> <label for="Name">Name</label> </div> <div class="editor-field"> <input class="text-Box single-line" data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="furaibo"> <span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span> </div> <p> <input type="submit" value="Save" class="ui-button ui-widget ui-state-default ui-corner-all" role="button" aria-disabled="false"> </p> </fieldset> </form>
AJAX POST用于拦截表单/提交.模态对话框在帖子完成后弹出并关闭.我想在发送帖子之前验证表单:
// force change the submit data to an ajax POST (usually 'save','delete' button) $('#modal-dialog').delegate('form','submit',function (e) { e.preventDefault(); var form = $(this); form.validate(); // does nothing if (form.valid()) { $.ajax({ url: form.attr('action'),type: "POST",data: form.serialize(),success: function (data) { $('#modal-dialog').dialog('close'); },error: function (jqXhr,textStatus,errorThrown) { alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "',errorThrown: '" + errorThrown + "')"); } }); } });
我这样做打破了什么吗? .valid()总是返回true.
我的web.config有:
<appSettings> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings>
我的网页来源有:
<link href="/DartsMVC/Content/themes/cupertino/jquery-ui-1.8.14.custom.css" rel="stylesheet" type="text/css"> <script src="/DartsMVC/Scripts/modernizr-1.7.min.js" type="text/javascript"></script> <script src="/DartsMVC/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> <script src="/DartsMVC/Scripts/jquery-ui-1.8.14.custom.min.js" type="text/javascript"></script> <script src="/DartsMVC/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script> <script src="/DartsMVC/Scripts/jquery.validate.js" type="text/javascript"></script> <script src="/DartsMVC/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
我的型号有:
[required] public string Name { get; set; }
经过更多的研究,我认为它可能与动态控制有关:
>由于data-val属性存在,因此它不是Form范围问题
>我会尝试调用$.validator.unobtrusive.parse(‘#formid’).如果这不行,我会用最后的手段:
> http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/