Asp.net MVC客户端验证不起作用,它仍然提交表单

时间:2015-08-12 06:20:48

标签: javascript jquery asp.net-mvc validation

@model MVC_Practice2.Models.MyOrder

@{
    Layout = null;
    Html.EnableClientValidation();
}
@using MVC_Practice2.Models;
<script type="text/javascript">
    $(function(){
        //$.validator.unobtrusive.parse("#order_detail");
        jQuery.validator.unobtrusive.parse();
        alert("load finished");
    });


</script>

    @using (Html.BeginForm("Update", "Order", FormMethod.Post, new { id = "order_detail" })) { 
    <input type="hidden" name="Id" value="@Model.Id">
    <table class="dv-table" style="width:100%;border:1px solid #ccc;padding:5px;margin-top:5px;">
        <tr>
            <td>@Html.LabelFor(x=>x.OrderDate)</td>

            <td>@Html.TextBoxFor(x => x.OrderDate, new { @class = "easyui-datetimebox", style = "width:200px" })
            @Html.ValidationMessageFor(x=>x.OrderDate)
            </td>
            <td>Status</td>
            <td>
            @if (Model.Status.Trim() == "Pending")
            {
                @Html.RadioButtonFor(x => x.Status, "P", new {@checked="checked" })<text>Pending</text>
            }
            else
            {
                @Html.RadioButtonFor(x => x.Status, "P", new { style = "width:100px" })<text>Pending</text>
            }

            @Html.RadioButtonFor(x => x.Status, "Cancelled", new { style = "width:100px" })<text>Cancelled</text>
            @Html.RadioButtonFor(x => x.Status, "Delivered", new { style = "width:100px" })<text>Delivered</text></td>
        </tr>
        <tr>
            <td>CustomerName</td>
            <td colspan="3">
                @Html.DropDownListFor(x => x.CustomerId, ViewBag.sl as IEnumerable<SelectListItem>)
            </td>
        </tr>
    </table>
    <div style="padding:5px 0;text-align:right;padding-right:30px">

        <input type="submit" class="easyui-linkbutton" iconcls="icon-save" plain="true">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" plain="true" onclick="cancelItem(@ViewBag.Index)">Cancel</a>
    </div>
        @Html.ValidationSummary()
    }

这是我的View代码,这是一个表单的AJAX加载,当我点击提交按钮时,它直接提交到后端,但没有按预期显示客户端错误消息,我已经添加了jquery.validate我的_Layout.cshtml文件中的.min.js和jquery.validate.unobtrusive.min.js如下所示

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />

    <script src="~/Scripts/jquery-1.11.3.min.js"></script>
    <script src="~/Scripts/jsrender.min.js"></script>

    <script src="~/Scripts/jquery.easyui-1.4.3.min.js"></script>
    <script src="~/Scripts/datagrid-detailview.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    <link href="~/Content/themes/black/easyui.css" rel="stylesheet" />
    <link href="~/Content/themes/icon.css" rel="stylesheet" />
    <title>@ViewBag.Title</title>
    @RenderSection("headsection", required: false)
</head>
<body>
    @RenderBody()



</body>
</html>

以下是我的模型代码

namespace MVC_Practice2.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;

    public partial class MyOrder
    {
        public int Id { get; set; }

        [DisplayName("高端时间")]
        [Required(ErrorMessage = "不能为空")]
        public System.DateTime OrderDate { get; set; }
        [StringLength(4, ErrorMessage = "太长了")]
        public string Status { get; set; }
        public int CustomerId { get; set; }

        public virtual MyCustomer MyCustomer { get; set; }
    }
}

以下是我的MainPage使用easyui ajax加载部分表单视图,如我在顶部提到的

@{
    ViewBag.Title = "EasyUI_Index";
}

<h2>EasyUI_Index</h2>
@section headsection
{
        <script type="text/javascript">
            function formatterdate(val, row) {
                if (val != null) {
                    var date = new Date(parseInt(val.replace("/Date(", "").replace(")/", ""), 10));
                    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
                    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
                    var hours = date.getHours();
                    var minutes = date.getMinutes();
                    var seconds = date.getSeconds();
                    // var milliseconds = date.getMilliseconds();
                    //return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
                    //当前需要这种时间格式MM/dd/yyyy hh:mm:ss
                    return month + "/" + day + "/" +date.getFullYear()+" "+ hours + ":" + minutes + ":" + seconds;
                }
            }
            $(function () {

                $("#tbList").datagrid({
                    title: 'DataGrid - DetailView',
                    view: detailview,
                    fitColumns: true,
                    nowrap: false,
                    detailFormatter: function (index, row) {
                        return '<div class="record_info"></div>';
                    },
                    onExpandRow: function(index,row){
                        var ddv = $(this).datagrid('getRowDetail', index).find('div.record_info');

                        ddv.panel({
                            border:false,
                            cache:true,
                            href: '/Order/Retrieve_Single_Order/' + row.OrderId+"?index="+index,
                            onLoad:function(){
                                $('#tbList').datagrid('fixDetailRowHeight', index);
                                $('#tbList').datagrid('selectRow', index);
                                $('#tbList').datagrid('getRowDetail',index).find('form').form('load',row);
                                console.log(row);
                                //$("#dt_box").datetimebox('setValue', '10/08/1990 23:15:10'); 
                                $("#OrderDate").datetimebox('setValue',formatterdate(row.OrderTime,null));

                            }

                        });
                        $('#tbList').datagrid('fixDetailRowHeight',index);
                        jQuery.validator.unobtrusive.parse();
                    },
                    url: "/Order/GetPageList",
                    width: 700,
                    height:600,

                    striped: true,

                    rownumbers: true,
                    columns: [[
                        { field: "OrderId",width:50},
                        { field: 'OrderTime', title: 'OrderTime', formatter: formatterdate, width: 50 },
                        { field: 'Status', title: 'Status', width: 50 },
                        { field: 'CustomerName', title: 'CustomerName', width: 50 },
                    ]],
                    toolbar: [{
                        iconCls: 'icon-edit',
                        text: 'Edit',
                        handler: function () { alert('编辑按钮') }
                    }, '-', {
                        iconCls: 'icon-remove',
                        text: 'Delete',
                        handler: function () {
                            //$('#tbList').datagrid('deleteRow', 1);// 索引从0开始
                            //$('#tbList').datagrid('reload');刷新一下
                            var row = $('#tbList').datagrid('getSelected');
                            if (!row) {
                                $.messager.alert('Wrong operation', 'You haven\'t choose row yet ', 'error');
                            }
                            else {
                                $.messager.confirm('Warning', 'Do you want to delele this row?', function (r) {
                                    if (r) {
                                        // delete操作;

                                        alert(row.OrderId);
                                        $.ajax({
                                            type: "POST",
                                            url: "/Order/Del/" + row.OrderId,


                                            success: function (msg) {

                                                $('#tbList').datagrid('reload');

                                            }
                                        });
                                    }
                                });
                            }

                        }
                    }],
                    pagination: true,
                    singleSelect: true,
                    pageSize: 3,
                    pageList: [3, 10, 30, 40, 50]
                })
            })

            function cancelItem(index) {

                $('#tbList').datagrid('collapseRow', index);

            }
        </script>
}

<table id="tbList" >
    <!--<tr>
        <th>DatabaseID</th>
        <th>Timestamp</th>
        <th>Subject</th>
        <th>Verb</th>
        <th>Object</th>
    </tr>-->
</table>
<style type="text/css">
    form {
        margin: 0;
        padding: 0;
    }

    .dv-table td {
        border: 0;
    }

    .dv-table input {
        border: 1px solid #ccc;
    }
</style>

以下是我的控制器代码

public class OrderController : Controller
    {
        public VideosEntities db = new VideosEntities();
        // GET: Order
        public ActionResult Index()
        {
            return View("EasyUI_Index");
        }


       [HttpPost]
        public ActionResult Update(MyOrder model)
        {
            if (ModelState.IsValid == false)
            {
                return Content("Please do not forbid the javascript validation.");
            }
            else
            {
                int id = Convert.ToInt32(Request.Params["Id"]);
                String datetime = Request.Params["OrderDate"];

                String status = Request.Params["Status"];
                int customerId = Convert.ToInt32(Request.Params["CustomerId"]);
                MyOrder updated_order = (from x in db.MyOrders where x.Id == id select x).FirstOrDefault();
                updated_order.OrderDate = Convert.ToDateTime(datetime);
                updated_order.Status = status;
                updated_order.CustomerId = customerId;
                db.SaveChanges();
                return Redirect("/Order/Index");
            }




        }

    }

1 个答案:

答案 0 :(得分:0)

好吧,正如我已经提到的那样,你应该将$.validator.unobtrusive.parse("#order_detail");放在ajaxComplete()处理程序的某处。

$.validator.unobtrusive.parse();没有选择器就无法工作因为它被写成接受选择器@Stephen Muecke已经提到它了。所以你可以在所有情况下像他一样写作

$('body').data('validator', null); //This line drop validators if you already have them in your DOM
$.validator.unobtrusive.parse('body');

半年前i've asked question about validation,你可能会感兴趣。