【问题标题】:ASP.NET MVC and Javascript - Submit button submitting form, onclick @URL.Action not firingASP.NET MVC 和 Javascript - 提交按钮提交表单,onclick @URL.Action 未触发
【发布时间】:2016-01-02 23:45:33
【问题描述】:

我有两个提交,一个在第 1 页提交表单,另一个在第 1 页提交表单并在第 2 页重定向到表单 2。

<input type="submit" value="Submit and Add Expense" onclick="window.location.href='@Url.Action("Create", "Expense")';"/>

问题是,当单击此辅助提交按钮时,它只会像第一个提交按钮一样提交表单。似乎重定向 @url.action 没有触发。想法?

【问题讨论】:

  • 不要让它成为提交按钮。提交按钮旨在提交表单而无需其他交互。您可以在 onclick 事件中 preventDefault,但从技术上讲,您不再使用提交了。
  • 我想更好的问题应该是,在这种情况下提交和重定向的最佳方式是什么?仔细观察一下,我似乎可以做到其中之一。
  • 所以你希望第二个按钮像正常提交一样发布,但之后重定向,而第一个按钮只是像正常一样发布并保持在同一页面上?
  • @AndyWiesendanger 是正确的。第一个按钮按预期工作,因为它只是一个基本的 type="submit"。

标签: javascript asp.net-mvc


【解决方案1】:

下面的代码应该可以解决问题。

<input type="submit" id="btnOne" value="One"/>

<input type="button" id="btnTwo" value="One"/>

<script>
    var sample = sample || {};
    sample.url = '@Url.Action("Create", "Expense")';
</script>

//you can move it to a separate file
<script>
$(function(){

    $("#btnTwo").click(function(){

        var form = $("form");
        form.submit();

         setTimeout(function() {


            window.location.href = sample.url;
        },100);


    });

});
</script>

【讨论】:

  • 感谢您的回复。这实际上并没有奏效。单击辅助按钮,表单没有提交也没有重定向到费用页面。
【解决方案2】:

我最终采用了简单的方法,将 value 属性分配给按钮,然后检查控制器中的按钮值。

// 查看

<input type="submit" value="Submit" />
<button name="button" value="SubmitAndExpense">Submit and Add Expense</button>

// 控制器

[HttpPost]
public ActionResult Create(string button)
{
   if (button != "SubmitAndExpense") {...}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 2015-08-19
    • 2015-05-07
    • 2010-09-12
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多