表单提交时需要校验数据是否已存在,如果已存在需要防止重复提交,做法比较简单,不再赘述。
1.Employee类
public class Employee
{
public int Id { set; get; }
[StringLength(10,MinimumLength=10)]
public string Name { set; get; }
[RegularExpression("^[1-9][0-9]{0,1}$")]
public Nullable<int> Age { set; get; }
}2.View
@model AspNetMvcModelValidate.Models.Employee
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
var name = $('#name').val();
$.post('@Url.Action("CheckEmployeeName")', {
name: name
},
function (data) {
console.log(data);
if (data) {
console.log("yes");
$("#myform").submit();
} else {
alert("Employee with name:" + name + "already exist.");//已有相同
}
})
});
});
</script>
<h2>Index2</h2>
@using (@Html.BeginForm("AddEmployee", "Home", FormMethod.Post, new { Id = "myform" }))
{
<table>
<tr>
<td>Name</td>
<td>@Html.TextBoxFor(s => s.Name, new { ID = "name" })</td>
</tr>
<tr>
<td>Age</td>
<td>@Html.TextBoxFor(s => s.Age)</td>
</tr>
<tr>
<td colspan="2"><input type="button" id="btn" value="submit" style="width:215px" /></td>
</tr>
</table>
}
3.控制器
public JsonResult CheckEmployeeName(string name)
{
var query = ModelsContainer.Employees.Where(x => x.Name == name).Count<Employee>();
return Json(query < 1, JsonRequestBehavior.AllowGet);
}
public ActionResult AddEmployee(Employee employee)
{
ModelsContainer.Employees.Add(employee);
return View(employee);
}4.数据源
public class ModelsContainer
{
public static List<Employee> Employees = new List<Employee>
{
new Employee{ Id = 1, Name = "Employee01", Age = 25 },
new Employee{ Id = 2, Name = "Employee02", Age = 25 }
};
}5.Result
本文介绍了一个基于ASP.NET MVC的应用案例,演示了如何通过客户端JavaScript和服务器端C#代码相结合的方式进行员工表单的数据验证,确保提交的数据有效且不重复。
495

被折叠的 条评论
为什么被折叠?



