mvc项目01_感受mvc的风景_jQuery validate验证_mvc+ajax
--感受mvc
1、数据库表+初始数据
2、ADO.NET EF +MVC2
显示数据列表
UserController.cs
adduser.UserName = userinfo.UserName;
adduser.Age=userinfo.Age;
}
3、view 前端校验
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#form1").validate({
rules: {
UserName: {
required: true,
minlength: 5,
remote: "/User/CheckUserName"
},
Age: {
required: true,
maxlength: 3
}
},
messages: {
UserName: {
required: "兔说:请输入用户名!",
minlength: "兔说:长度不能小于5位!",
remote: "兔说:此用户名已经存在"
},
Age:{
required: "兔说:年纪不能为空",
maxlength: "兔说:个数必须小于3"
}
}
});
});
</script>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm("create", "user", FormMethod.Post, new { id = "form1" }))
{%>
<%: Html.ValidationSummary(true)%>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.UserName)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.UserName)%>
<%: Html.ValidationMessageFor(model => model.UserName)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Age)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Age)%>
<%: Html.ValidationMessageFor(model => model.Age)%>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
4、后台校验
//让目标类和当前类共享元数据信息
[MetadataType(typeof(UserValidate))]
public partial class UserInfo
{
}
public class UserValidate
{
//目标类里的所有属性都可以在下面进行校验规则定义
[Required(ErrorMessage = "*")]
public int id { get; set; }
[Required(ErrorMessage = "* 名字不能为空")]
public string UserName { get; set; }
}
[Range(10,130)]
[Required(ErrorMessage="*必填项")]
public int Id { get; set; }
[StringLength(10,ErrorMessage="*<10")]
public string Content { get; set; }
[RegularExpression(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$")]
]
public string B{ get; set; }
5、结果
-- 01:初始数据
---------------------------02 mvc 使用ajax 用户名是否存在----------------------------
-----------------------03数据验证-------------------------
---------------------------04 mvc 输入有效数据-------------------------
----------------------------05显示列表------------------------------------------