您的位置:首页 > 编程语言 > ASP

AspNetMvc 防止重复提交

2015-05-21 16:30 351 查看
表单提交时需要校验数据是否已存在,如果已存在需要防止重复提交,做法比较简单,不再赘述。

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





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: