jQuery 客户端验证在使用 Bootstrap 的 ASP.NET MVC5 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19737907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Client-side validation not working in ASP.NET MVC5 with Bootstrap
提问by SimonGoldstone
Running Visual Studio 2013, I created a new ASP.NET MVC (5) project, with Bootstrap.
运行 Visual Studio 2013,我使用 Bootstrap 创建了一个新的 ASP.NET MVC (5) 项目。
However, I'm unable to get unobtrusive client-side validation working.
但是,我无法使不显眼的客户端验证工作。
The model has [Required]attributes on the relevant properties and the view has ValidationMessageFor...tags for each field in the form.
模型具有[Required]相关属性的属性,视图具有ValidationMessageFor...表单中每个字段的标签。
However, submitting the form causes the form to postback to server before validation messages appear.
但是,提交表单会导致表单在验证消息出现之前回发到服务器。
Using NuGet, I've installed jquery.validateand jquery.validate.unobtrusiveand added them to the jquery bundle in App_Start.
使用 NuGet,我已经安装jquery.validate并将jquery.validate.unobtrusive它们添加到App_Start.
Yet it continues to stubbornly post back to server. F12 dev tools shows no JS errors/warnings.
然而它继续顽固地回发到服务器。F12 开发工具没有显示 JS 错误/警告。
Has anybody else come across this issue (can't see anything in SO relating to MVC 5 specifically) and do you have any ideas?
有没有其他人遇到过这个问题(在 SO 中看不到任何与 MVC 5 相关的内容),您有什么想法吗?
回答by Gary McGill
I had the same problem. Comparing the generated HTML with a site that worked, I noticed that at the end of the document, there was this:
我有同样的问题。将生成的 HTML 与一个有效的网站进行比较,我注意到在文档的末尾,有这个:
<script src="/bundles/jqueryval"></script>
...whereas the bundle should have been expanded like this:
...而bundle应该像这样展开:
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
I looked in App_Start/BundleConfig.cs, and sure enough, the JQuery validation bundle had not been defined in RegisterBundles. I had to add:
我查看了 App_Start/BundleConfig.cs,果然,JQuery 验证包没有在RegisterBundles. 我不得不补充:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
Why this was missing, I don't know. I started with a new, clean project.
为什么缺少这个,我不知道。我从一个新的、干净的项目开始。
It's pretty shoddy that there's no compile-time error when you reference an undefined bundle. Even an always-on run-time error would be better than silent failure. So much time wasted!
当您引用未定义的包时没有编译时错误,这是非常粗制滥造的。即使是永远在线的运行时错误也比静默失败要好。浪费了这么多时间!
EDIT: turns out I didn't have the JQuery validation scripts in my project, either. I had to add them via NuGet ("Microsoft JQuery Unobtrusive Validation").
编辑:原来我的项目中也没有 JQuery 验证脚本。我不得不通过 NuGet(“Microsoft JQuery Unobtrusive Validation”)添加它们。
回答by user2934829
I was having same problem. The solution is to add .js reference to master page (_Layout.cshtml)
我遇到了同样的问题。解决方案是在母版页(_Layout.cshtml)中添加.js引用
- jquery.validate.js
- jquery.validate.unobtrusive.js
- jquery.validate.js
- jquery.validate.unobtrusive.js
回答by flip
Have you verified <add key="ClientValidationEnabled" value="true" />in web.config?
你<add key="ClientValidationEnabled" value="true" />在 web.config 中验证了吗?
Otherwise, this provides a good overview: ASP.NET MVC 3: Required steps for unobtrusive client-side validation of dynamic/AJAX content. Also valid for MVC5.
否则,这提供了一个很好的概述:ASP.NET MVC 3:动态/AJAX 内容的不显眼的客户端验证所需的步骤。也适用于 MVC5。
回答by Maulik Anand
At the bottom of the page add:
在页面底部添加:
@Scripts.Render("~/bundles/jqueryval")
and everything will work fine.
一切都会好起来的。
回答by nasolev
Since tour using MVC instead of adding to every edit view, you could add in the view/shared folder at _Layout.cshtml.
由于游览使用 MVC 而不是添加到每个编辑视图,因此您可以在 _Layout.cshtml 的视图/共享文件夹中添加。
just add
只需添加
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jqueryval")
at the bottom of _Layout.cshtml, on top of
在 _Layout.cshtml 的底部,在
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/jqueryval")
in this case the script will effect every page that uses that layout.
在这种情况下,脚本将影响使用该布局的每个页面。
回答by yardpenalty.com
I know this is a little late to the game but this does add more to validation and I found it to be very helpful. Sometimes conflicting javascript/jQuery Plugin/API references (eg:searchMeme.js) that reference other jquery versions can cause problems so I create unique bundles for account login actions. These are the steps I would take:
我知道这对游戏来说有点晚了,但这确实增加了验证,我发现它非常有帮助。有时,引用其他 jquery 版本的 javascript/jQuery 插件/API 引用(例如:searchMeme.js)的冲突会导致问题,因此我为帐户登录操作创建了独特的包。这些是我将采取的步骤:
1.Create a separate layout ~/Views/Shared/_AccountLayout.cshtmlfor AccountController.cs.
1.为AccountController.cs创建一个单独的布局~/Views/Shared/_AccountLayout.cshtml。
2.Create new ~/Account/_ViewStart.csthmlwith:
2. 使用以下命令创建新的~/Account/_ViewStart.csthml:
@{
Layout = "~/Views/Shared/_AccountLayout.cshtml";
}
3.Create two bundles for css & js in BundleConfig.csfor AccountController:
3.在BundleConfig.cs 中为 AccountController创建两个 css & js bundle :
bundles.Add(new StyleBundle("~/Content/accountcss").Include(
"~/Content/site.css",
"~/Content/bootstrap.css",
"~/Content/font-awesome.css")); /*if using font-awesome */
bundles.Add(new ScriptBundle("~/bundles/accountjs").Include(
"~/Scripts/jquery-1.10.2.js",
"~/Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js",
"~/Scripts/bootstrap.js"));//must be after jquery validate
4.Reference the bundles in both ends of head& bodyin _AccountLayout.cshtmlas such:
4.参考在两端的束头和身体在_AccountLayout.cshtml这样:
<title>@ViewBag.Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
@Styles.Render("~/Content/accountcss")
@Scripts.Render("~/bundles/modernizr")
@this.RenderSection("MetaContent", false)
@this.RenderSection("Styles", false)
</head>
@Scripts.Render("~/bundles/accountjs")
@this.RenderSection("Scripts", false)
</body>
*NOTE: Make sure bootstrap is after jqueryval in bundle
*注意:确保引导程序在捆绑包中的 jqueryval 之后
5.Make sure you have @Html.ValidationMessageForfor each input field within ~/Account/Login.cshtml, ~/Account/Register.cshtml, etc... respectively.
5.确保您@Html.ValidationMessageFor在~/Account/Login.cshtml、~/Account/Register.cshtml等中的每个输入字段都分别...。
<div class="form-group">
@Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
</div>
</div>
6.Use DataAnnotations to create additional custom validation errors [RegularExpression(@"^([\w]{2,20})@?([\w]{2,20}).?[a-zA-Z]{2,3}$", ErrorMessage="")]:
6.使用 DataAnnotations 创建额外的自定义验证错误[RegularExpression(@"^([\w]{2,20})@?([\w]{2,20}).?[a-zA-Z]{2,3}$", ErrorMessage="")]:
[Required(ErrorMessage = "*Username is required."), RegularExpression(@"^[\w+]{3,10}\s?([\w+]{3,15})$", ErrorMessage = "*Username can only be Alphanumeric"),StringLength(25, ErrorMessage = "The {0} must be at least {2} characters long and no bigger than {1} characters.", MinimumLength = 5)]
public string UserName { get; set; }
7. (optional)Lastly, if you changed the DataAnotation for Password then you MUSTalso change the Password Policy in ~/App_Start/IdentityConfig.csas such:
7.(可选)最后,如果您更改了密码的 DataAnotation,那么您还必须更改~/App_Start/IdentityConfig.cs 中的密码策略,如下所示:
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
8. (optional)Also, check out this articleon Roles etc..
回答by veb
I was having the same issue when I was playing with my first MVC project. The issue was at the end that I didn't include the input elements to the form element. Yes, very stupid. Make sure you create the form, for instance :
我在玩我的第一个 MVC 项目时遇到了同样的问题。问题是最后我没有将输入元素包含到表单元素中。是的,非常愚蠢。确保您创建了表单,例如:
@using (Html.BeginForm())
{
@Html.EditorFor(model => model.FieldA)
@Html.ValidationMessageFor(model => model.FieldA)
@Html.EditorFor(model => model.FieldB)
@Html.ValidationMessageFor(model => model.FieldB)
}
回答by Kien
I had the same problem, my solution is clear all history in browser (cache, cookies, form, ...) and everything work correctly.
我遇到了同样的问题,我的解决方案是清除浏览器中的所有历史记录(缓存、cookie、表单等),并且一切正常。
回答by jgarza
I think that @Html.ValidationMessageFor is missing from the template. I do get the errors, but not the messages.
我认为模板中缺少 @Html.ValidationMessageFor。我确实收到了错误,但没有收到消息。
回答by Garry
I am providing this answer for future readers.I was dealing with the same issue and found the problem is with the sequence of the render scripts. Make Sure
我正在为未来的读者提供这个答案。我正在处理同样的问题,发现问题出在渲染脚本的顺序上。确保
@Scripts.Render("~/bundles/jquery")
is before
是之前
@Scripts.Render("~/bundles/jqueryval")
in _layout.cshtml . The layout bottom part should look like follow.
在 _layout.cshtml 中。布局底部应如下所示。
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")

