大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE稳定放心使用
表单提交时需要校验数据是否已存在,如果已存在需要防止重复提交,做法比较简单,不再赘述。
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
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/187762.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...