表单提交时需要校验数据是否已存在,如果已存在需要防止重复提交,做法比较简单,不再赘述。
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
今天的文章.net防止重复提交_java后端防止重复提交分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/74039.html