【问题标题】:Pop-up dialog using jQuery issue使用 jQuery 问题的弹出对话框
【发布时间】:2013-06-26 11:17:27
【问题描述】:

您好,我的页面有问题。我在同一页面中有一个视图页面和 2 个表单。

问题是我有一个主窗体和另一个由 JQuery 显示的窗体。我的问题是当我打开对话框,提交表单并返回视图时,对话框消失了。我不知道如何返回仍然会显示打开的对话框的结果。

我需要你的帮助!

以下是我在应用程序中使用的代码。

.CSTHML 表单

@using (Html.BeginForm("Login2", "Account", FormMethod.Post, new { @id = "loginForm" }))
{
    <a id="submitlink" href="#" class="button button-large">Sign In</a>
}

// This is the pop-up dialog box
@using (Html.BeginForm("TroubleSubmit", "Account", FormMethod.Post, new { @id = "troubleSubmitForm" }))
{
    <a id="troubleSubmitLink" href="#" class="button">OK</a>
}

JQUERY

$('a#submitlink').click(function () {
            $('#loginForm').submit();
        });

$('a#troubleSubmitlink').click(function () {
            $('#troubleSubmitForm').submit();
        });

以下是处理对话框表单提交的控制器操作代码:

public ActionResult SignInTrouble(some parameter...)
    {
        // some operation and validation here

        return View(); // ??? What view will I return? When I return "Login" it will reload the page and close the dialog box.
    }

再次,我如何返回仍将显示对话框的视图

【问题讨论】:

  • 提交表单后,页面会重新加载。如果您不想重新加载页面,则应该使用 AJAX 请求。
  • 或者 iFrame,我认为 jQuery 对话框会处理它们
  • 你能给我一些示例代码吗?

标签: asp.net asp.net-mvc-4


【解决方案1】:

您以传统(非 AJAX)方式提交表单,因此页面将重新加载。所以你需要以 AJAX 方式发帖。

$("#submitlink").on("click", function () {
    var loginForm = $("#loginForm");

    $.ajax({
        url: loginForm.attr("action"),
        type: "post",
        data: loginForm.serialize(),
    })
    .done(function(result) {
        // do something with the returned response
    });
});

成功的响应由.done() 处理,但返回什么以及如何处理结果取决于您。最简单的选择是返回一个局部视图,因此它只是一个插入现有 div 容器的 html 片段。

.done(function(result) {
    $("#someDiv").html(result);
});

我经常返回 JSON,并将视图呈现为 html 字符串 { status: 0, message: "Success", html: "&lt;div&gt;..." }。如果您只需要一个简单的“是/否”,则可以省略 JSON 中的 html 片段。

public ActionResult SignInTrouble(some parameter...)
{
    // some operation and validation here

    return Json({
        status: 1,
        message: "Validation Error"
    });
}

那么你的回复就会有更多的可能性

.done(function(result) {
    var status = result.status;
    var message = result.message;
    if (status == 0) {
      // OK
    } else {
      // ERROR
    }
    $("#messageDiv").text(message);
}

【讨论】:

    【解决方案2】:

    只是因为页面被重新加载,这种情况下必须使用ajax表单,所以它只会处理ajax表单的动作,然后将结果返回到表单中,而不需要重新加载页面

    @Ajax.BeginForm("TroubleSubmit","Account", new AjaxOptions(){ ...... })
    

    【讨论】:

    • 你的意思是说,用你的建议替换这个 "@using (Html.BeginForm("TroubleSubmit", "Account", FormMethod.Post, new { @id = "troubleSubmitForm" }))"对吧?
    • 这就是我的意思,但您必须更改 AjaxOptions 选项中的某些内容以适应您的要求。
    • 我现在能够使 Ajax.BeginForm 工作,我现在的问题是如何将验证错误消息返回到对话框?
    • 在具有属性的AjaxOptions 中,UpdateTargetId 将是服务器返回的结果的占位符(html 元素的 ID),在服务器端,您执行简单的事情,只需根据您的验证返回一个字符串结果返回Content("message from server")
    猜你喜欢
    • 2012-06-07
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    相关资源
    最近更新 更多