在尝试避免使用JavaScript多年之后,Iv开始在MVC asp.net中使用Query进行验证,因为似乎没有一种官方的验证方法,Iv对jQuery的出色表现感到惊讶。
首先,有没有一种方法可以让Intellisense为jQuery及其验证插件工作,所以我不必学习api?
其次,我如何为此创建验证摘要,它当前将错误附加到文本框的右侧。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <script type="text/javascript">
$().ready(function() {
$("#CreateLog").validate({
rules: {
UserName: {
required: true,
minLength: 2,
}
},
messages: {
UserName: {
required:"Please enter a username",
minLength:"Your username must consist of at least 2 characters",
}
}
});
});
<form id="CreateLog" action="Create" method="post" />
<label>UserName</label><br />
<%=Html.TextBox("UserName")%>
<br />
<input type=submit value=Save />
</form> |
我尝试将其添加到脚本中:
1
| errorLabelContainer: $("#CreateLog div.error") |
和这个到HTML:
但这没有用。
尝试在选项中同时指定包装器和标签容器。 我还向错误容器的样式添加了display:none;,以使jQuery决定何时显示它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| $().ready(function() {
$("#CreateLog").validate({
errorLabelContainer: $("ul", $('div.error-container')),
wrapper: 'li',
rules: {
UserName: {
required: true,
minLength: 2,
}
},
messages: {
UserName: {
required:"Please enter a username",
minLength:"Your username must consist of at least 2 characters"
}
}
});
}); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
<ul>
</ul>
<form id="CreateLog" action="Create" method="post" />
<label>UserName</label><br />
<%=Html.TextBox("UserName")%>
<br />
<input type=submit value=Save />
</form> |
那应该工作。
您可能想在CodeBetter.com上及其示例应用程序画布上查看Karl Seguin的ASP.NET MVC验证方法。
验证-第1部分-入门
验证-第2部分-客户端
验证-第3部分-服务器端
VS2008中有一个针对JQuery IntelliSense的Visual Studio 2008修补程序。 这可能已经与SP1捆绑在一起。
关于jquery(和其他插件)的intellisense:为了在您自己的脚本文件中也具有完整的intellisense,只需对要从中进行智能化处理的每个文件在.js文件顶部添加以下行:
1
| /// <reference path="[insert path to script file here]" /> |
简单,但非常有用=)