如何在负载上提交MVC视图



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

无法获得未定义或null参考的财产'提交

这是我的代码:

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

的帖子中使用代码工作的代码
@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,它也起作用,但注意到11显然是两次射击该事件,导致了两个弹出窗口。不管。也许通过向后工作,您可以找到自己的问题。

尝试theway

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

使用以下代码,表格将提交

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

mySubmitButton.trigger("click");

最新更新