0
@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()
    }

This is my View code,this is a AJAX load of the form,when I click the submit button,it directly submit to the backend with out showing me the clientside error message as expected ,I have already add the jquery.validate.min.js and jquery.validate.unobtrusive.min.js in my _Layout.cshtml file shown as below

<!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>

The following is my Model code

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; }
    }
}

And the following is my MainPage which use easyui ajax load that partial form view as I mentioned in the top

@{
    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>

The following is my Controller code

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");
            }




        }

    }
Austin
  • 3
  • 4
  • I have the following configuration in the web.config – Austin Aug 12 '15 at 06:21
  • You do not (and should not have) `jQuery.validator.unobtrusive.parse();` in your script - that is already handled by `jquery.validate.unobtrusive.js` –  Aug 12 '15 at 06:23
  • @StephenMuecke i gess he need if he load this view with Ajax. moreover i think he should place `jQuery.validator.unobtrusive.parse();` in .`ajaxComplete()` handler. – teo van kot Aug 12 '15 at 06:25
  • 1
    And what do you mean _this is a AJAX load of the form_? Is this a partial view that you load using ajax, if so you need to re-parse the validator after the content is loaded (not before). Show how you load the form –  Aug 12 '15 at 06:26
  • @StephenMuecke yes,this is a partial view which is loaded using ajax – Austin Aug 12 '15 at 08:47
  • Then show your code. –  Aug 12 '15 at 08:51
  • Here is the Mainpage,please have a look. – Austin Aug 12 '15 at 09:04
  • @teovankot you are genius,sir! After I put the **$.validator.unobtrusive.parse("#order_detail");**. in the easyui onload() event handler(which is triggered while the ajax loading is done),it works!!! – Austin Aug 12 '15 at 09:29
  • @teovankot I still have question is that why when I use `$.validator.unobtrusive.parse(); ` method it does not work,but `$.validator.unobtrusive.parse("#order_detail"); `works fine? – Austin Aug 12 '15 at 09:35
  • @StephenMuecke Now the validation works for the `@Html.TextBoxFor(x => x.OrderDate, new { @class = "easyui-datetimebox", style = "width:200px" }` ,however another domain `@Html.RadioButtonFor(x => x.Status, "Delivered", new { style = "width:100px" })` the validation does not work, apparently the string length is longer than the restriction of the MyOrder Class Status property's annotation. But why the client side did not show me this error message,instead,the form still submitted to the backend – Austin Aug 12 '15 at 09:56
  • Firstly `$.validator.unobtrusive.parse();` does not work because the method accepts an element/selector. And you should be clearing the validator first - refer [this answer](http://stackoverflow.com/questions/31768946/required-field-validations-not-working-in-jquery-popup-mvc-4/31769058#31769058) –  Aug 12 '15 at 10:00

1 Answers1

0

Well, as i already mention, you should place $.validator.unobtrusive.parse("#order_detail"); somewhere in ajaxComplete() handler.

$.validator.unobtrusive.parse(); not working without selector becouse it was written to accept selector @Stephen Muecke already mention it. So you can write like his in All cases

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

Half a year ago i've asked question about validation, it could be interesting to you.

Community
  • 1
  • 1
teo van kot
  • 12,350
  • 10
  • 38
  • 70