如何在加载时提交 MVC 视图?

How do I submit a MVC view on load?

我有一个视图,它有一个带有单个隐藏提交按钮的表单。我想在页面加载时提交表单。但是,我在 Javascript 中所做的任何提交都会给我这个错误:

Unable to get property 'submit' of undefined or null reference

这是我的代码:

PrintApplication.cshtml

    @using (Html.BeginForm("PrintApplications", "Admin", FormMethod.Post, new { @id = "PrintApplications", @class = "form-horizontal ", @commandname = "ModelContract", @target = "_blank" }))
    {
      <input id="btnPrintApplications" type="submit" class="btn btn-primary" value="PrintApplications" name="submit" style="visibility: hidden" />
    }

<script>

    document.onreadystatechange = function () {
        document.form.submit();
    }

</script>

代替document.form.submit,我也试过

var form = document.getElementById("PrintApplications");
form.submit();

document.forms["PrintApplications"].submit();

this.form.submit();

和其他变体(例如,在表单名称前加上#)

我的代码有什么问题。有没有其他方法可以自动提交页面(无需用户单击任何按钮)?

编辑:这是我的原始代码。它在 IE 中不起作用,这是引发我遇到的问题的原因。没有错误,但是表单没有提交。不过,这在 Chrome 中运行良好。

    $(document).ready(function () {
    $("#btnPrintApplications").click();
    });

编辑 2:这是我使用来自@barry

的 post 中的代码工作的代码
@using (Html.BeginForm("PrintApplications", "Admin", FormMethod.Post, new { @id = "PrintApplications", @class = "form-horizontal ", @commandname = "ModelContract", @target = "_blank" }))
{
    @*<input id="btnPrintApplications" type="submit" class="btn btn-primary" value="PrintApplications" name="submit" style="visibility: hidden" />*@
    <div>
        If applications do not appear in a separate tab or window, please click the button below.
    </div>
    <input id="btnPrintApplications" type="submit" class="btn btn-primary" value="Print Applications" name="print" />
}

<script>
  mySubmitButton = document.getElementById("btnPrintApplications");
    mySubmitButton.click();
</script>

编辑 3:这是使用来自@chris-pratt 的示例的代码。

@using (Html.BeginForm("PrintApplications", "Admin", FormMethod.Post, new { @id = "PrintApplications", @class = "form-horizontal ", @commandname = "ModelContract", @target = "_blank" }))
{
    <div>
        If applications do not appear in a separate tab or window, please click the button below.
    </div>
    <input id="btnPrintApplications" type="submit" class="btn btn-primary" value="Print Applications" name="print" />
}

<script>
    window.onload = function () {
        document.forms['PrintApplications'].submit();
    }
</script>

以下简单的 HTML 文档功能完全符合您的要求:

<html>
<body>
    <form id="Test" action="http://google.com" target="_blank">
        <input type="hidden" name="q" value="test" />
    </form>
    <script>
        window.onload = function () {
            document.forms['Test'].submit();
        }
    </script>
</body>
</html>

我最初使用 document.onreadystatechange,它也有效,但注意到 IE 11 显然会触发该事件两次,从而产生两个弹出窗口。而不管。也许通过向后工作你可以找到你的问题。

试试这个

mySubmitButton = document.getElementById("PerfSubmit");         
mySubmitButton.click();         

使用以下代码将提交表单

$('form')[0].submit();

mySubmitButton.trigger("click");