必填字段和客户端验证

时间:2013-09-10 11:20:40

标签: c# asp.net asp.net-mvc

我已将[Required(ErrorMessage = "*")]放入模型

[Required(ErrorMessage = "*")]
[Display(Name = "Amount")]
public decimal Amount { get; set; }

在webconfig中将这些字段设置为true

 <add key="ClientValidationEnabled" value="true" />
 <add key="UnobtrusiveJavaScriptEnabled" value="true" />

 @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)

               <tr>
                    <td>@Html.LabelFor(model => model.Amount)</td>
                    <td>@Html.EditorFor(model => model.Amount )
                @Html.ValidationMessageFor(model => model.Amount )</td>

                        <input onclick="return validate();" style=" margin:20px; width:120px; height:40px;" type="submit" value="ثبت فیش" />

    }

按钮单击不检查验证,将此添加到控制器以进行服务器端验证

 if (ModelState.IsValid)
            {
                obj.DateAdded = DateTime.Now;
                obj.OrderID = id;
                RingSportEntities objEntity = new RingSportEntities();
                objEntity.Payments.Add(obj);
                var p = (from o in objEntity.Orders where o.OrderId == id select o).First();
                p.Status = 2;
                objEntity.SaveChanges();
                return View();
            }
            else { return View(obj); }

现在,它适用于服务器端验证,为什么客户端现在可以工作?

2 个答案:

答案 0 :(得分:1)

试试这个

<input onsubmit="return $(this).closest("form").valid();" style=" margin:20px; width:120px; height:40px;" type="submit" value="submit!" />

答案 1 :(得分:0)

试试这个,

查看

 @using (Html.BeginForm("YourPage", "Controller", FormMethod.Post, new { id = "FrmIndex" }))
        { 
<input type="submit" value="Save" style="float: left;" id="btnSave" title="btn" />
    }

<强>脚本

<script type="text/javascript">
        $(document).ready(function () {


            $("#btnSave").click(function () {

                var validation = $("#FrmIndex"); // My From Id
                if (!validation.valid()) {
                    return false;
                }

            });
        });
    </script>

您必须添加这两个脚本以进行验证。

<script src="@Url.Content("~/Script/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Script/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>