Html.BeginForm在当前窗口中提交表单,并用另一个URL打开一个新窗口

时间:2016-10-18 13:20:37

标签: html asp.net-mvc razor form-submit

首先要明确一点,不是它不是某种垃圾邮件,而是来自客户的请求应该以这种方式处理。

我有一个MVC项目,我想在当前窗口中提交一个表单,并打开一个带有静态URL的新窗口,例如www.google.se。就像现在一样,我有一个模态,显示的形式如下:

<div id="openModal" class="modalDialog">
            <div>
                @using (Html.BeginForm("Action", "controller", new { id = Model.Id }, FormMethod.Post))
                {
                    <h4>
                        Are you sure?
                    </h4>
                    <br />
                    <input type="submit" value="Yes" class="btn btn-default" />
                    <a href="#close" title="Close" class="btn btn-default">Nope</a>
                }
            </div>
        </div>

所以我正在寻找要在主窗口上执行的表单的提交,然后再打开另一个窗口。新打开的窗口应该没有工具栏或地址栏。

编辑:如果在提交表单之前或之后打开窗口并不重要,因为在提交表单时没有验证。

3 个答案:

答案 0 :(得分:2)

您只需在target上添加beginform

Html.BeginForm("Action", "controller", new { id = Model.Id }, FormMethod.Post, **new {target = "_blank"}**)

这将打开一个新的标签/窗口。

答案 1 :(得分:0)

如果您可以使用JQuery,则可以为提交按钮添加处理程序,此代码不会阻止表单提交。

$(document).ready(function() {
  $("#submit").on("click", function() 
    {
       var tab = window.open(url, '_blank');
       tab.focus();
    }});

或为表单添加处理程序

$('#openModal').submit(function(e){
           var tab = window.open(url, '_blank');
           tab.focus();
   });
});

没有JQuery

document.getElementById("submit").onclick = function() { 
var tab = window.open(url, '_blank');
tab.focus();

};

答案 2 :(得分:0)

First, the only way to open a new window is with JavaScript. Whether or not the window has controls and chrome is also configured by that JavaScript when it creates the new window. However, bear in mind that this is ultimately controlled by the client and it can be enforced that new windows must have the buttons and chrome and even that they can't be new windows at all, but only new tabs. You ultimately have no true control over that; you can only suggest.

Second, the form post will by default cause the entire view to reload, interrupting any currently running JavaScript and preventing any yet to run JavaScript from running. That means you can't directly open a window after the POST because there's no room to do so. However, you can have the resulting new view open a new window. For example, if the post takes the user to a confirmation page, that confirmation page could have JavaScript that opens a new window.

Alternatively, you can handle the post via AJAX, which would allow you to stay on the page, and then have a new window be opened inside the success callback. However, if you're no going to use jQuery, I would suggest using some sort of library at that point, because handling a cross-browser AJAX request correctly requires a stupid amount of boilerplate code.