26

我的 Razor 视图中有一个表单声明

<form method="post" action="/Lot/LotList?auctionEventId=@auctionEventId" id="filterForm">

(顺便说一句,我选择这样写而不是使用Html.BeginFrom,因为我需要给它一个 id 并且不知道如何使用它Html.BeginFrom- 但这不是这里的问题)

在此表单之外,我有一个提交此表单的按钮(表单中还有一个提交按钮)

<input type="button" onclick="$('#filterForm').submit();" value="Show all" />

现在,问题是,如果此按钮用于提交表单,我希望表单中的操作更改为

action="/Lot/LotList?auctionEventId=@auctionEventId&showAll=true"

如何更改操作并传递此附加参数?有没有更好的方法来做这一切?

4

6 回答 6

41

将查询字符串参数附加到表单操作上,并尝试在运行时更改它是棘手的(但并非不可能)。使用隐藏字段要容易得多:

<form method="post" action="/Lot/LotList" id="filterForm">
  <input type="hidden" name="auctionEventId" value="@auctionEventId" />
  ...

所以现在你所要做的就是为“showAll”添加另一个隐藏字段

<form method="post" action="/Lot/LotList" id="filterForm">
  <input type="hidden" name="auctionEventId" value="@auctionEventId" />
  <input type="hidden" name="showAll" value="false" id="showAllField" />
  ...

只需在 showAll 按钮上连接一个 jquery 事件:

<input id="showAllButton" type="button"/>

jQuery:

$('#showAllButton').click(function(){
     $('#showAllField').val("true");
     $('#filterForm').submit();
});
于 2012-10-31T16:49:49.583 回答
9

我知道您说这不是问题,但您可以添加Html.BeginForm如下属性:

 @using (Html.BeginForm("ActionName","ControllerName", FormMethod.Post, new { id = "filterform" })){
于 2013-12-16T23:22:38.837 回答
8

如何放置一个隐藏的输入

<form method="post" action="/Lot/LotList?auctionEventId=@auctionEventId" id="filterForm">

<input type="hidden" id="showAll" name="showAll" value=""/>

在你的按钮上

<input type="button" onclick="submitForm()" value="Show all" />

在你的脚本某处

function submitForm(){
$('#showAll').val('true');
$('#filterForm').submit();

}
于 2012-10-31T16:49:27.573 回答
4

如果您在表单中,则可以将路由添加到按钮元素。您可以使用 formAction 和 formMethod 覆盖表单的本机操作。您还可以使用其他 formActions 和 formMethods 拥有多个按钮

<form action="/somewhere" method="get">
    <input type="type" name="name" value=" " />


    <button formaction="/Lot/LotList?auctionEventId=@auctionEventId&showAll=true" formmethod="post">Show All</button>
</form>

于 2016-06-24T02:27:26.440 回答
0

如果同一个表单有多个提交按钮,并且需要为每个按钮传递不同的参数,则可以使用 asp-route 属性来完成此任务。

 <input type="submit" value="Save"/>

 <input id="btnComplete" type="submit"
        asp-route-addNewOneAfterSave="@true"
        value="Save And Create New One">

请记住在 OnPost 方法中包含您的参数,例如:

public async Task<IActionResult> OnPostAsync(bool? addNewOneAfterSave)
        {
             //Your code ....
        }

您可以从本文中阅读更多关于 asp-route 锚标记助手的信息。

于 2020-02-01T08:03:15.733 回答
0

你好,我发现这很好用

 @using (Html.BeginForm("ActionName","ControllerName",  new { id = "filterform" },FormMethod.Post)){

我已经厌倦了在参数之前执行“FormMethod.Post”,但它不起作用并且从未传递值。只有通过反复试验,我才设法解决它并发现它应该像我发布的代码一样。

希望有帮助

于 2018-02-08T08:21:25.327 回答