当前位置: 首页 > 知识库问答 >
问题:

jquery模式复制表单中的mvc提交表单partialview

邢起运
2023-03-14

我按照Darin Dimitrov的示例在模式对话框中提交表单(带有验证):

使用Ajax。使用ASP。NETMVC3Razor

它完美地工作在例外。当我提交带有故意错误的表单时,我在对话框中得到了该表单的两份副本:

以下是我的部分观点:

@model MvcAppTemplate.ViewModels.SupportClass1ViewModel
<script src="~/Scripts/Jquery/jquery.validate.min.js"></script>
<script src="~/Scripts/Jquery/jquery.validate.unobtrusive.js"></script>
<script>
    $(document).ready(function () {
        $('#SupportClass1Name').focus();

        $('form').submit(function () {
            if ($(this).valid()) {
                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: $(this).serialize(),
                    success: function (result) {
                        $('#result').html(result);
                    }
                });
            }
            return false;
        });
    });
</script>
<div id="result"></div>
@using (Html.BeginForm("CreateDialog", "SupportClass1", FormMethod.Post, new { @class = "form-horizontal" }))
{
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true, "The following errors occurred:", new { style = "color: red" })
    <fieldset>
        <legend>MyMainClass1</legend>
        @Html.ValidationMessage("CustomError", new { @class = "error" })
        @Html.HiddenFor(model => model.IsNew)
        <div class="form-group">
            <div class="col-lg-3 control-label">
                @Html.LabelFor(model => model.SupportClass1Name)
            </div>
            <div class="col-lg-6">
                @Html.TextBoxFor(model => model.SupportClass1Name, new { style = "width: 400px;", @maxlength = "50" })
                @Html.ValidationMessageFor(model => model.SupportClass1Name)
            </div>
        </div>
        <div class="form-group">
            <div class="col-lg-3 control-label">
                @Html.LabelFor(model => model.Active)
            </div>
            <div class="col-lg-6">
                @Html.EditorFor(model => model.Active, new { style = "width: 150px;" })
                @Html.ValidationMessageFor(model => model.Active)
            </div>
        </div>
        <p>
            <input type="submit" value="Create" class="btn btn-primary" />
            @Html.ActionLink("Cancel", "Search", "SupportClass1", null, new { @class = "btn btn-default" })
        </p>
    </fieldset>
}

我称之为模态的视图来自:

@model MvcAppTemplate.ViewModels.SupportClass1ViewModel

@{
    ViewBag.Title = "Test";
}
<link href="~/Scripts/jquery-ui-1.11.1.custom/jquery-ui.min.css" rel="stylesheet" />
<link href="~/Content/dataTables.bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.11.1.custom/jquery-ui.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#dialog').dialog({
            autoOpen: false,
            width: 600,
            height: 400,
            resizable: true,
            title: 'Support Class 1',
            modal: true,
            open: function (event, ui) {
                $(this).load("@Url.Action("CreateDialog", "SupportClass1")");
             },
             buttons: {
                 "Close": function () {
                     $(this).dialog("close");
                 }
             }
         });
        $("#opener").click(function () {
            $("#dialog").dialog("open");
        });
    });
</script>

<div id="dialog" title="Create" >Please wait</div>
<button id="opener">Show Class</button>

最后是我的控制器:

// create in a pop up dialog
public ActionResult CreateDialog()
{
    var lvm = new SupportClass1ViewModel
    {
        IsNew = true,
    };
    return PartialView("_CreateDialog",lvm);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateDialog(SupportClass1ViewModel lvm)
{
    SupportClass1 supportClass1 = new SupportClass1();
    // Use Injector to handle mapping between viewmodel and model
    supportClass1.InjectFrom(lvm);

    try
    {
        if (ModelState.IsValid)
        {
            supportClass1Service.CreateSupportClass1(supportClass1);
            // redirect to the myMainClass1 view
            //return RedirectToAction("Details", "SupportClass1", new { id = supportClass1.SupportClass1Id });
            return Content("Thanks", "text/html");

        }
    }
    catch (DataException de)
    {
        //Log the error (add a variable name after DataException)
        var s = de.InnerException.ToString();

        ModelState.AddModelError("CustomError", "Unable to save changes. Try again, and if the problem persists, see your system administrator. Error: " + s);
    }
    // rehydrate the view
    lvm.IsNew = true;
    //return Content("Thanks", "text/html");
    return PartialView("_CreateDialog", lvm);

出现错误时,部分视图会加载两次:一次在result div中,一次从原始@using Html加载。BeginForm()。我通过在result div周围放置一个可见的边框来验证这一点。

任何帮助都很感激。

共有2个答案

令狐灿
2023-03-14

这一行是问题:

success: function (result) {
                    $('#result').html(result);
                }

这个处理程序在成功和失败的情况下都被调用,因此您最终会显示两次表单,一次来自原始渲染,然后在错误发生时显示在结果div中。

将控制器代码更改为:

 try
{
    if (ModelState.IsValid)
    {
        supportClass1Service.CreateSupportClass1(supportClass1);
        // redirect to the myMainClass1 view
        //return RedirectToAction("Details", "SupportClass1", new { id = supportClass1.SupportClass1Id });
        return Json(new {success = true, message ="Thanks" } );

    }
}
catch (DataException de)
{
    //Log the error (add a variable name after DataException)
    var s = de.InnerException.ToString();

    ModelState.AddModelError("CustomError", "Unable to save changes. Try again, and if the problem persists, see your system administrator. Error: " + s);
}

return Json(new {success = "false", message = "Error"}); // do a concatenation of the model state errors

那么你的成功处理程序可以看起来像

 success: function (result) {
                    if(result.success) {
                        $('#result').html(result.message);
                    }
                    else {
                        // provide some highlighting or what have you or just set the message
                        $('#result').addClass("error").html(result.message);
                    }
                }
范承教
2023-03-14

我想出了一个解决办法。正如我在评论中所说,我将部分视图的形式包装在一个div中:

<div id="myForm">
@using (Html.BeginForm("CreateDialog", "SupportClass1", FormMethod.Post, new { @class = "form-horizontal" }))
{
some content...
}
</div>

然后,在我的jquery表单提交函数中,我清除了div,然后用控制器的部分视图表单(存在验证错误的表单:

$('form').submit(function () {
    if ($(this).valid()) {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                $('#myForm').html('');
                $('#result').html(result);
            }
        });
    }
    return false;
});
 类似资料:
  • 问题内容: 此代码正确吗?我正在尝试提交,如果文本区域再次为空,我也想提交。 我正在尝试上传: 谢谢… 问题答案: 用 代替 如果您使用的是最新版本的jquery。

  • 问题内容: 我有一个带有名称和未定义输入数量的表单。 我想做某种jQuery.get或ajax或类似的事情,它将通过Ajax调用页面,并发送表单的所有输入。 我想一种方法是做类似的事情 但是我不完全知道所有的表格输入。是否有仅发送所有表单输入的功能部件或功能? 问题答案: 您可以使用Ajax表单插件中的ajaxForm / ajaxSubmit函数或jQuery序列化函数。 AjaxForm :

  • 问题内容: 我的表单需要服务器处理一些时间。我需要确保用户等待并且不会再次单击按钮来尝试重新提交表单。我尝试使用以下jQuery代码: 当我在Firefox中尝试此操作时,所有功能都被禁用,但是该表单未与应该包含的任何POST数据一起提交。我不能使用jQuery提交表单,因为我需要将按钮与表单一起提交,因为有多个提交按钮,并且我确定POST中包含哪个值使用了哪个按钮。我需要像平常一样提交表单,并且

  • pre { white-space: pre-wrap; } 本教程向您展示如何通过 easyui 提交一个表单(Form)。我们创建一个带有 name、email 和 phone 字段的表单。通过使用 easyui 表单(form)插件来改变表单(form)为 ajax 表单(form)。表单(form)提交所有字段到后台服务器,服务器处理和发送一些数据返回到前端页面。我们接收返回数据,并将它显

  • 问题内容: 我在理解Spring 3 MVC中的表单如何工作时遇到问题。 我想做的是创建一个控制器,该控制器将用户名显示给他。我以某种方式做到了,但我真的不了解它是如何工作的。所以.. 我有一个看起来像这样的表格: 我也有一个看起来像这样的控制器: 为了向用户显示欢迎消息,我在JSP页面中使用以下代码: 而且行得通(我忽略了XML配置文件,因为它们与问题无关)。 我认为表单中的“ modelAtt

  • 我不理解Spring3 MVC中表单提交的工作原理。 我想做的,是创建一个控制器,它将使用用户的名字并显示给他。不知怎么的,我做了,但我真的不明白它是怎么工作的。所以.. 我还有一个控制器,看起来像这样: 为了向用户显示欢迎消息,我在JSP页面中使用以下代码: 并且可以工作(我省略了XML配置文件,因为它们与问题无关)。 从“showhellopage”方法中,我得到一个(常见的)异常“neuth