首页新闻找找看学习计划

MVC4在使用ajax.beginform()提交表单时,在easyui弹出框中无法进行数据验证?

0
悬赏园豆:100 [待解决问题]

尝试过如果数据不放在弹出对话框中,Model验证有效。如果在弹出页面中加入验证的js文件,Model验证也有效,但是会出现重复提交等问题;如果将验证js文件不放在弹出页面中,验证的错误信息怎么也不会显示出来,哪位大哥有遇到过类似的,是不是js冲突,还是怎么的。。

问题补充:

@Scripts.Render("~/bundles/jqueryval")

这条语句放在弹出框中的页面时,能进行数据验证,但会出现重复提交,弹出框的页面代码如下

View Code
@model Web.Models.Pictrue
@{
    Layout = "";
}
@*<link href="/Content/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="@Url.Content("~/Scripts/bootstrap.min.js")"></script>*@
@*@Scripts.Render("~/bundles/jqueryval")*@
@*<link href="@Url.Content("~/Scripts/Validation/css/validationEngine.jquery.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/Validation/js/jquery.validationEngine-en.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Validation/js/jquery.validationEngine.js")" type="text/javascript"></script>*@
<script src="/Content/uploadify/jquery.uploadify.js" type="text/javascript"></script>
<link href="/Content/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
        if ($("#img_64").attr("src") == "") {
            //上传
            $('#MyUpload').uploadify({

                //上传处理程序
                'uploader': '/Pictrues/Upload',
                'swf': '/Content/uploadify/uploadify.swf',
                'multi': false,
                //'auto': false,
                'buttonText': '请选择上传文件',
                'fileTypeDesc': '图片文件',
                'fileTypeExts': '*.gif; *.jpg; *.png;*.jpeg',
                'onUploadStart': function (file) {
                    $(".loading").html("<img src='/Images/ajax-loader.gif' />");
                },
                'fileSizeLimit': '3MB',
                //返回一个错误,选择文件的时候触发
                'onSelectError': function (file, errorCode, errorMsg) {
                    switch (errorCode) {
                        //case -100:
                        //    alert("上传的文件数量已经超出系统限制的" + $('#MyUpload').uploadify('settings', 'queueSizeLimit') + "个文件!");
                        //    break;
                        case -110:
                            alert("文件 [" + file.name + "] 大小超出系统限制的" + $('#MyUpload').uploadify('settings', 'fileSizeLimit') + "大小!");
                            break;
                            //case -120:
                            //    alert("文件 [" + file.name + "] 大小异常!");
                            //    break;
                        case -130:
                            alert("文件 [" + file.name + "] 类型不正确!");
                            break;
                    }
                },
                //检测FLASH失败调用
                'onFallback': function () {
                    alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
                },
                'onUploadSuccess': function (file, data, response) {
                    eval("data=" + data);
                    //alert('文件 ' + file.name + ' 已经上传成功,并返回 ' + response + ' 保存文件名称为 ' + data.SaveName);
                    $(".loading").empty();
                    $('#upimgdiv').show();
                    $("#Url").val("/Uploads/" + data.SaveName);
                    $("#img_64").attr("src", "/Uploads/64/" + data.SaveName);
                    $('#MyUpload').hide();
                }
            });
        }
        else {
            ('#MyUpload').hide();
        }
        $("#dele").click(function () {
            $.ajax(
        {
            url: '@Url.Action("DeleteFile", "Pictrues")',
            type: "POST",
            data: {
                filepath: $("#Url").val(),
                filepaths: $("#img_64").attr("src")
            },
            beforeSend: function (XMLHttpRequest) {
                $.jBox.tip("正在删除...", 'loading');
            },
            success: function (result) {
                $.jBox.closeTip();
                $("#Url").val("");
                $("#img_64").attr("src", "");
                $("#upimgdiv").hide();
                $('#MyUpload').show();
            }
        });
        });
    });
        function fun(event, queueID, fileObj, response, data) {
            if (response != "") {
                showInfo("成功上传" + response, true); //showInfo方法设置上传结果     
            }
            else {
                showInfo("文件上传出错!", false);
            }
        }
        //显示提示信息,textstyle2为绿色,即正确信息;textstyl1为红色,即错误信息
        function showInfo(msg, type) {
            var msgClass = type == true ? "textstyle2" : "textstyle1";
            $("#result").removeClass();
            $("#result").addClass(msgClass);
            $("#result").html(msg);
        }
        //如果点击‘导入文件’时选择文件为空,则提示
        function checkImport() {
            if ($.trim($('#fileInput1Queue').html()) == "") {
                alert('请先选择要导入的文件!');
                return false;
            }
            return true;
        }
</script>
@using (Ajax.BeginForm((string)ViewBag.Action, "Pictrues", null, new AjaxOptions { HttpMethod = "Post", OnSuccess = "DataUpdateds",OnFailure="DataFail" }, new { @class = "form-horizontal" }))
{
    @Html.ValidationSummary(true)
      @Html.HiddenFor(model => model.Id)
    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Description)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Description)
        @Html.ValidationMessageFor(model => model.Description)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Url)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Url)
        @Html.ValidationMessageFor(model => model.Url)
        <input type="file" id="MyUpload" name="myUploadd" />
        <div class="loading"></div>
        <div id="upimgdiv" style="display: none">

            <img style="width: 64px; height: 64px;" id="img_64" src="" border="0" /><br />
            (64*64)
            <a href="#" id="dele">删除</a>
        </div>
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.CategoryId)
    </div>
    <div class="editor-field">
          @Html.DropDownList("CategoryId", String.Empty)
        @Html.ValidationMessageFor(model => model.CategoryId)
    </div>
    <p>
        <input id="subbtnid" type="submit" value="Create" style="display: none" />
    </p>
}

如果放在主页面中,不会进行数据验证,主页面代码如下

View Code
@model IEnumerable<Web.Models.Pictrue>

@{
    Layout = "";
}
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
<link href="@Url.Content("~/Content/jBox/Skins/Blue/jbox.css")" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="@Url.Content("~/Content/jBox/jquery.jBox-2.3.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Content/jBox/i18n/jquery.jBox-zh-CN.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/BBScripts/ZHITJS.js")"></script>
@Styles.Render("~/Content/easyuithemes/metro/css")
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.easyui.min.js")"></script>
@Scripts.Render("~/bundles/easyui")
<script type="text/javascript">

    function DataUpdateds() {
        $.messager.alert("众惠科技", "操作成功!", 'info', function () {
            $('#dg').datagrid('reload');
            $("#dialogedit").html("").hide().dialog('close');
        });
    };
    function DataFail() {
        $.messager.alert("众惠科技", "操作失败,请按照要求填写表单!", 'error');
    };
</script>
<script type="text/javascript">
    var selectedid;
    var cardview = $.extend({}, $.fn.datagrid.defaults.view, {
        renderRow: function (target, fields, frozen, rowIndex, rowData) {
            selectedid = rowData.Id;
            var cc = [];
            cc.push('<td colspan=' + fields.length + ' style="padding:10px 5px;border:0;">');
            if (!frozen) {
                var aa = rowData.Url.split('/Uploads/');
                var img = '/Uploads/64/' + aa[1];

                cc.push('<img src="' + img + '" style="width:120px;float:left">');
                cc.push('<div style="float:left;margin-left:20px;">');
                for (var i = 0; i < fields.length; i++) {
                    var copts = $(target).datagrid('getColumnOption', fields[i]);
                    cc.push('<p><span class="c-label">' + copts.title + ':</span> ' + rowData[fields[i]] + '</p>');

                }

                cc.push('</div>');
            }
            //cc.push('<div style="float:right">');
            //cc.push('<a href="#" onclick="onDataUpdate()">编辑</a> ');
            //cc.push('<a href="#"  onclick="onDataDelete()">删除</a> ');
            //cc.push('</div>');
            cc.push('</td>');
            return cc.join('');
        }
    });
    function onDataUpdate() {
        var selecteds = $('#dg').datagrid('getSelected');
        var indexs = $('#dg').datagrid('getRowIndex', selecteds);
        if (indexs < 0) {
            $.messager.alert(g_MsgBoxTitle, "请选择一行!", 'error');
        }
        else {
            $.messager.confirm(g_MsgBoxTitle, '确定要修改编号为' + selecteds.Id + "的图片吗?", function (r) {
                if (r) {
                    var urlupdate = '@Url.Action("Update", "Pictrues")' + "?Id=" + selecteds.Id;
                    $.ajax({
                        url: urlupdate,
                        type: "GET",
                        beforeSend: function (XMLHttpRequest) {
                            $.jBox.tip("请稍等...", 'loading');
                        },
                        complete: function (XHR, TS) {
                            //$('#dg').datagrid('clearSelections');
                        },
                        success: function (result) {
                            $.jBox.closeTip();
                            $("#dialogedit").html(result).show().dialog({
                                width: 600, height: 400, modal: true, resizable: true,  closable: true,
                                buttons: [
                        { text: "修改", iconCls: 'icon-ok', plain: true,
                            handler: function () {
                                $("#subbtnid").trigger("click");
                                $.parser.parse();
                            }
                        },
                        { text: '取消', iconCls: 'icon-cancel', plain: true,
                            handler: function () {
                                $("#dialogedit").html("").hide().dialog('close');
                            }
                        }]
                               
                            });
                        }
                    });
                    //$('#dg').datagrid('clearSelections');
                }
            });
        }
    }
    function onDataAdd() {
                    var urladd = '@Url.Action("Add", "Pictrues")';
                    $.ajax({
                        url: urladd,
                        type: "GET",
                        beforeSend: function (XMLHttpRequest) {
                            $.jBox.tip("请稍等...", 'loading');
                        },
                        success: function (result) {
                            $.jBox.closeTip();
                            $("#dialogedit").html(result).show().dialog({
                                width: 600, height: 400, modal: true, resizable: true, closable: true,
                                buttons: [
                        {
                            text: "创建", iconCls: 'icon-ok', plain: true,
                            handler: function () {

                                $("#subbtnid").trigger("click");
                            }
                        },
                        {
                            text: '取消', iconCls: 'icon-cancel', plain: true,
                            handler: function () {
                                $("#dialogedit").html("").hide().dialog('close');
                            }
                        }],
                                onOpen: function () {
                                    $.parser.parse($("#dialogedit"));
                                }
                            });
                           
                        }
                    });
                    //$('#dg').datagrid('clearSelections');
                }
            

    $(function () {

        $('#dg').datagrid({
            url:"/Pictrues/GetPictrues",
            view: cardview,
            toolbar: [{
                iconCls: 'icon-add',
                handler: onDataAdd
            }, '-', {
                iconCls: 'icon-edit',
                handler: onDataUpdate
            }, '-', {
                iconCls: 'icon-remove',
                handler: onDataDelete
            }]
        });
    });

    function appendQueryString(url, parameters) {
        url += "?"
        for (var key in parameters) {
            if (parameters[key] === null || parameters[key] === undefined || parameters[key] === "") {
                continue;
            }
            url += key + "=" + encodeURIComponent(parameters[key]) + "&";
        }
        return url;
    }
    function onDataDelete() {
        var selected = $('#dg').datagrid('getSelected');
        var index = $('#dg').datagrid('getRowIndex', selected);
        if (index < 0) {
            $.messager.alert(g_MsgBoxTitle, "请选择一行!", 'error');
        }
        else {
            $.messager.confirm(g_MsgBoxTitle, '确定要删除编号为' + selected.Id + "的图片吗?", function (r) {
                if (r) {
                    $.ajax({
                        url: appendQueryString('@Url.Action("Delete")', { Id: selected.Id }),
                        type: "GET",
                        beforeSend: function (XMLHttpRequest) {
                            $.jBox.tip("请稍等...", 'loading');
                        },
                        success: function (result) {
                            $.jBox.closeTip();
                            var ab = selected.Url.split('/Uploads/');
                            var imgb = '/Uploads/64/' + ab[1];
                            $.ajax({
                                url: '@Url.Action("DeleteFile", "Pictrues")',
                                type: "POST",
                                data: {
                                    filepath: selected.Url,
                                    filepaths: imgb
                                },
                                beforeSend: function (XMLHttpRequest) {
                                    $.jBox.tip("正在删除...", 'loading');
                                },
                                success: function (result) {
                                    $.jBox.closeTip();
                                    $('#dg').datagrid('deleteRow', index);
                                }
                            });

                        }
                    });
                }
            });

        }
    }
</script>
<style type="text/css">
    .c-label {
        display: inline-block;
        width: 100px;
        font-weight: bold;
    }
</style>
<table id="dg" style="width: 800px; height: 400px" pagination="true"  title="DataGrid - CardView" singleselect="true" fitcolumns="true">
    <thead>
        <tr>
            <th field="Id" width="60">编号</th>
            <th field="Name" width="80">图片名称</th>
            <th field="Description" align="right" width="70">图片描述</th>
            <th field="CategoryId" align="right" width="70">图片类别</th>
            <th field="Url" align="center" width="50">图片路径</th>
        </tr>
    </thead>
</table>
    @*<div class="modal fade hide" id="dialogedit" data-backdrop="static" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" ></div>*@
    <div  style="display:none" id="dialogedit"  ></div>
love begins coding的主页 love begins coding | 初学一级 | 园豆:11
提问于:2013-03-05 11:27
< >
分享
所有回答(2)
0

加载完弹出框后调用 $.parser.parse() 试试

自由_ | 园豆:440 (菜鸟二级) | 2013-03-06 10:34

不行吧

支持(0) 反对(0) love begins coding | 园豆:11 (初学一级) | 2013-03-06 11:20

@love begins coding: 

这里改一下:

            success: function (result) {
                            $.jBox.closeTip();
                            $("#dialogedit").html(result).show().dialog({
                                width: 600, height: 400, modal: true, resizable: true, closable: true,
                                buttons: [
                        {
                            text: "创建", iconCls: 'icon-ok', plain: true,
                            handler: function () {

                                $("#subbtnid").trigger("click");
                            }
                        },
                        {
                            text: '取消', iconCls: 'icon-cancel', plain: true,
                            handler: function () {
                                $("#dialogedit").html("").hide().dialog('close');
                            }
                        }],
                                onOpen: function () {
                                    $.parser.parse($("#dialogedit"));
                                }
                            });
                           
                        }

改成下面的试试,把$.parser.parse() 放在 dialog之后:

            success: function (result) {
                            $.jBox.closeTip();
                            $("#dialogedit").html(result).show().dialog({
                                width: 600, height: 400, modal: true, resizable: true, closable: true,
                                buttons: [
                        {
                            text: "创建", iconCls: 'icon-ok', plain: true,
                            handler: function () {

                                $("#subbtnid").trigger("click");
                            }
                        },
                        {
                            text: '取消', iconCls: 'icon-cancel', plain: true,
                            handler: function () {
                                $("#dialogedit").html("").hide().dialog('close');
                            }
                        }]
                            });
                           $.parser.parse();
                        }
支持(0) 反对(0) 自由_ | 园豆:440 (菜鸟二级) | 2013-03-06 11:39
0

其实是页面已经验证了,为什么会没有显示验证消息呢?

通过浏览器调试工具可以清楚的看到ajax的请求已经发出,返回的也是部分试图的界面,

这就要求ajax提交的form成功之后,需要将返回的试图重新会知道显示页。

ajax是异步操作,需要将操作返回的数据显示在页面。

 

DataUpdateds改写为DataUpdateds(data){

  // message提示代码

  $('#dialogedit')..empty().append(data);

}

 

诸葛小亮 | 园豆:202 (菜鸟二级) | 2015-01-28 14:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册