A Razor view has 3 buttons inside a form. All button's actions will need form values which are basically values coming input fields.
Razor视图在表单中有3个按钮。所有按钮的操作都需要表单值,表单值基本上是输入字段的值。
Every time I click any of buttons it redirected me to default action. Can you please guide how I can submit form to different actions based on button press ?
每次我点击任何一个按钮,它都会将我重定向到默认动作。请您指导我如何根据按钮按下不同的动作提交表单?
I really appreciate your time, guidance and help.
非常感谢您的时间、指导和帮助。
12 个解决方案
#1
76
You could also try this:
你也可以试试这个:
<input type="submit" name="submitbutton1" value="submit1" />
<input type="submit" name="submitbutton2" value="submit2" />
Then in your default function you call the functions you want:
然后在默认函数中调用你想要的函数:
if( Request.Form["submitbutton1"] != null)
{
// Code for function 1
}
else if(Request.Form["submitButton2"] != null )
{
// code for function 2
}
#2
57
This elegant solution works for number of submit buttons:
这个优雅的解决方案适用于提交按钮的数量:
@Html.Begin()
{
// Html code here
<input type="submit" name="command" value="submit1" />
<input type="submit" name="command" value="submit2" />
}
And in your controllers' action method accept it as a parameter.
在控制器的动作方法中接受它作为参数。
public ActionResult Create(Employee model, string command)
{
if(command.Equals("submit1"))
{
// Call action here...
}
else
{
// Call another action here...
}
}
#3
15
in the view
在视图中
<form action="/Controller_name/action" method="Post>
<input type="submit" name="btn1" value="Ok" />
<input type="submit" name="btn1" value="cancel" />
<input type="submit" name="btn1" value="Save" />
</form>
in the action
在行动
string str =Request.Params["btn1"];
if(str=="ok"){
}
if(str=="cancel"){
}
if(str=="save"){
}
#4
10
You can use JS + Ajax. For example, if you have any button you can say it what it must do on click event. Here the code:
您可以使用JS + Ajax。例如,如果您有任何按钮,您可以告诉它它必须在单击事件上做什么。下面的代码:
<input id="btnFilterData" type="button" value="myBtn">
Here your button in html: in the script section, you need to use this code (This section should be at the end of the document):
这里是html中的按钮:在脚本部分,您需要使用此代码(此部分应该在文档的末尾):
<script type="text/javascript">
$('#btnFilterData').click(function () {
myFunc();
});
</script>
And finally, you need to add ajax function (In another script section, which should be placed at the begining of the document):
最后,您需要添加ajax函数(在另一个脚本部分中,应该在文档的开始处放置):
function myFunc() {
$.ajax({
type: "GET",
contentType: "application/json",
url: "/myController/myFuncOnController",
data: {
//params, which you can pass to yu func
},
success: function(result) {
error: function (errorData) {
}
});
};
#5
4
The cleanest solution I've found is as follows:
我找到的最干净的解决方案如下:
This example is to perform two very different actions; the basic premise is to use the value to pass data to the action.
这个例子是执行两个非常不同的动作;基本前提是使用值将数据传递给操作。
In your view:
在你的观点:
@using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
if (isOnDli)
{
<button name="removeDli" value="@result.WeNo">Remove From DLI</button>
}
else
{
<button name="performDli" value="@result.WeNo">Perform DLI</button>
}
}
Then in your action:
然后在你的行动:
public ActionResult DliAction(string removeDli, string performDli)
{
if (string.IsNullOrEmpty(performDli))
{
...
}
else if (string.IsNullOrEmpty(removeDli))
{
...
}
return View();
}
This code should be easy to alter in order to achieve variations along the theme, e.g. change the button's name to be the same, then you only need one parameter on the action etc, as can be seen below:
这段代码应该很容易修改,以实现主题上的变化,例如,将按钮的名称更改为相同,然后在操作上只需要一个参数等,如下所示:
In your view:
在你的观点:
@using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
<button name="weNo" value="@result.WeNo">Process This WeNo</button>
<button name="weNo" value="@result.WeNo">Process A Different WeNo This Item</button>
}
Then in your action:
然后在你的行动:
public ActionResult DliAction(string weNo)
{
// Process the weNo...
return View();
}
#6
3
Try wrapping each button in it's own form in your view.
尝试将每个按钮封装到视图中它自己的窗体中。
@using (Html.BeginForm("Action1", "Controller"))
{
<input type="submit" value="Button 1" />
}
@using (Html.BeginForm("Action2", "Controller"))
{
<input type="submit" value="Button 2" />
}
#7
3
You could use normal buttons(non submit). Use javascript to rewrite (at an 'onclick' event) the form's 'action' attribute to something you want and then submit it. Generate the button using a custom helper(create a file "Helper.cshtml" inside the App_Code folder, at the root of your project) .
您可以使用普通的按钮(不提交)。使用javascript重写(在“onclick”事件中)表单的“action”属性到您想要的东西,然后提交它。使用自定义帮助器生成按钮(创建一个文件“帮助器”。在App_Code文件夹中的cshtml“,位于项目的根)。
@helper SubmitButton(string text, string controller,string action)
{
var uh = new System.Web.Mvc.UrlHelper(Context.Request.RequestContext);
string url = @uh.Action(action, controller, null);
<input type=button onclick="(
function(e)
{
$(e).parent().attr('action', '@url'); //rewrite action url
//create a submit button to be clicked and removed, so that onsubmit is triggered
var form = document.getElementById($(e).parent().attr('id'));
var button = form.ownerDocument.createElement('input');
button.style.display = 'none';
button.type = 'submit';
form.appendChild(button).click();
form.removeChild(button);
}
)(this)" value="@text"/>
}
And then use it as:
然后把它当作:
@Helpers.SubmitButton("Text for 1st button","ControllerForButton1","ActionForButton1")
@Helpers.SubmitButton("Text for 2nd button","ControllerForButton2","ActionForButton2")
...
Inside your form.
在你的表格。
#8
0
This answer will show you that how to work in asp.net with razor, and to control multiple submit button event. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
这个答案将向您展示如何使用razor在asp.net中工作,以及如何控制多个提交按钮事件。例如,我们有两个按钮,一个按钮将我们重定向到“PageA”。cshtml”和其他将把我们重定向到“PageB.cshtml”。
@{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
#9
0
In case you're using pure razor, i.e. no MVC controller:
如果你使用纯razor,即没有MVC控制器:
<button name="SubmitForm" value="Hello">Hello</button>
<button name="SubmitForm" value="World">World</button>
@if (IsPost)
{
<p>@Request.Form["SubmitForm"]</p>
}
Clicking each of the buttons should render out Hello and World.
单击每个按钮应该呈现Hello和World。
#10
0
Didn't see an answer using tag helpers (Core MVC), so here it goes (for a delete action):
没有看到使用标记帮助器(核心MVC)的答案,所以在这里(对于删除操作):
On HTML:
HTML:
<form action="" method="post" role="form">
<table>
@for (var i = 0; i < Model.List.Count(); i++)
{
<tr>
<td>@Model.List[i].ItemDescription</td>
<td>
<input type="submit" value="REMOVE" class="btn btn-xs btn-danger"
asp-controller="ControllerName" asp-action="delete" asp-route-idForDeleteItem="@Model.List[i].idForDeleteItem" />
</td>
</tr>
}
</table>
</form>
On Controller:
控制器:
[HttpPost("[action]/{idForDeleteItem}"), ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(long idForDeleteItem)
{
///delete with param id goes here
}
Don't forget to use [Route("[controller]")]
BEFORE the class declaration - on controller.
不要忘记在类声明- on控制器之前使用[Route("[controller])]。
#11
0
Simplest way is to use the html5 FormAction
and FormMethod
最简单的方法是使用html5 FormAction和FormMethod
<input type="submit"
formaction="Save"
formmethod="post"
value="Save" />
<input type="submit"
formaction="SaveForLatter"
formmethod="post"
value="Save For Latter" />
<input type="submit"
formaction="SaveAndPublish"
formmethod="post"
value="Save And Publish" />
[HttpPost]
public ActionResult Save(CustomerViewModel model) {...}
[HttpPost]
public ActionResult SaveForLatter(CustomerViewModel model){...}
[HttpPost]
public ActionResult SaveAndPublish(CustomerViewModel model){...}
There are many other ways which we can use, see this article ASP.Net MVC multiple submit button use in different ways
我们还可以使用许多其他方法,请参阅本文ASP。Net MVC多重提交按钮的使用方式不同
#12
0
This is what worked for me.
这对我起了作用。
formaction="@Url.Action("Edit")"
Snippet :
代码片段:
<input type="submit" formaction="@Url.Action("Edit")" formmethod="post" value="Save" class="btn btn-primary" />
<input type="submit" formaction="@Url.Action("PartialEdit")" formmethod="post" value="Select Type" class="btn btn-primary" />
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit( Quote quote)
{
//code
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PartialEdit(Quote quote)
{
//code
}
Might help some one who wants to have 2 different action methods instead of one method using selectors or using client scripts .
对于那些想要使用两个不同的操作方法而不是使用选择器或使用客户端脚本的方法的人来说,这可能会有所帮助。
#1
76
You could also try this:
你也可以试试这个:
<input type="submit" name="submitbutton1" value="submit1" />
<input type="submit" name="submitbutton2" value="submit2" />
Then in your default function you call the functions you want:
然后在默认函数中调用你想要的函数:
if( Request.Form["submitbutton1"] != null)
{
// Code for function 1
}
else if(Request.Form["submitButton2"] != null )
{
// code for function 2
}
#2
57
This elegant solution works for number of submit buttons:
这个优雅的解决方案适用于提交按钮的数量:
@Html.Begin()
{
// Html code here
<input type="submit" name="command" value="submit1" />
<input type="submit" name="command" value="submit2" />
}
And in your controllers' action method accept it as a parameter.
在控制器的动作方法中接受它作为参数。
public ActionResult Create(Employee model, string command)
{
if(command.Equals("submit1"))
{
// Call action here...
}
else
{
// Call another action here...
}
}
#3
15
in the view
在视图中
<form action="/Controller_name/action" method="Post>
<input type="submit" name="btn1" value="Ok" />
<input type="submit" name="btn1" value="cancel" />
<input type="submit" name="btn1" value="Save" />
</form>
in the action
在行动
string str =Request.Params["btn1"];
if(str=="ok"){
}
if(str=="cancel"){
}
if(str=="save"){
}
#4
10
You can use JS + Ajax. For example, if you have any button you can say it what it must do on click event. Here the code:
您可以使用JS + Ajax。例如,如果您有任何按钮,您可以告诉它它必须在单击事件上做什么。下面的代码:
<input id="btnFilterData" type="button" value="myBtn">
Here your button in html: in the script section, you need to use this code (This section should be at the end of the document):
这里是html中的按钮:在脚本部分,您需要使用此代码(此部分应该在文档的末尾):
<script type="text/javascript">
$('#btnFilterData').click(function () {
myFunc();
});
</script>
And finally, you need to add ajax function (In another script section, which should be placed at the begining of the document):
最后,您需要添加ajax函数(在另一个脚本部分中,应该在文档的开始处放置):
function myFunc() {
$.ajax({
type: "GET",
contentType: "application/json",
url: "/myController/myFuncOnController",
data: {
//params, which you can pass to yu func
},
success: function(result) {
error: function (errorData) {
}
});
};
#5
4
The cleanest solution I've found is as follows:
我找到的最干净的解决方案如下:
This example is to perform two very different actions; the basic premise is to use the value to pass data to the action.
这个例子是执行两个非常不同的动作;基本前提是使用值将数据传递给操作。
In your view:
在你的观点:
@using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
if (isOnDli)
{
<button name="removeDli" value="@result.WeNo">Remove From DLI</button>
}
else
{
<button name="performDli" value="@result.WeNo">Perform DLI</button>
}
}
Then in your action:
然后在你的行动:
public ActionResult DliAction(string removeDli, string performDli)
{
if (string.IsNullOrEmpty(performDli))
{
...
}
else if (string.IsNullOrEmpty(removeDli))
{
...
}
return View();
}
This code should be easy to alter in order to achieve variations along the theme, e.g. change the button's name to be the same, then you only need one parameter on the action etc, as can be seen below:
这段代码应该很容易修改,以实现主题上的变化,例如,将按钮的名称更改为相同,然后在操作上只需要一个参数等,如下所示:
In your view:
在你的观点:
@using (Html.BeginForm("DliAction", "Dli", FormMethod.Post, new { id = "mainForm" }))
{
<button name="weNo" value="@result.WeNo">Process This WeNo</button>
<button name="weNo" value="@result.WeNo">Process A Different WeNo This Item</button>
}
Then in your action:
然后在你的行动:
public ActionResult DliAction(string weNo)
{
// Process the weNo...
return View();
}
#6
3
Try wrapping each button in it's own form in your view.
尝试将每个按钮封装到视图中它自己的窗体中。
@using (Html.BeginForm("Action1", "Controller"))
{
<input type="submit" value="Button 1" />
}
@using (Html.BeginForm("Action2", "Controller"))
{
<input type="submit" value="Button 2" />
}
#7
3
You could use normal buttons(non submit). Use javascript to rewrite (at an 'onclick' event) the form's 'action' attribute to something you want and then submit it. Generate the button using a custom helper(create a file "Helper.cshtml" inside the App_Code folder, at the root of your project) .
您可以使用普通的按钮(不提交)。使用javascript重写(在“onclick”事件中)表单的“action”属性到您想要的东西,然后提交它。使用自定义帮助器生成按钮(创建一个文件“帮助器”。在App_Code文件夹中的cshtml“,位于项目的根)。
@helper SubmitButton(string text, string controller,string action)
{
var uh = new System.Web.Mvc.UrlHelper(Context.Request.RequestContext);
string url = @uh.Action(action, controller, null);
<input type=button onclick="(
function(e)
{
$(e).parent().attr('action', '@url'); //rewrite action url
//create a submit button to be clicked and removed, so that onsubmit is triggered
var form = document.getElementById($(e).parent().attr('id'));
var button = form.ownerDocument.createElement('input');
button.style.display = 'none';
button.type = 'submit';
form.appendChild(button).click();
form.removeChild(button);
}
)(this)" value="@text"/>
}
And then use it as:
然后把它当作:
@Helpers.SubmitButton("Text for 1st button","ControllerForButton1","ActionForButton1")
@Helpers.SubmitButton("Text for 2nd button","ControllerForButton2","ActionForButton2")
...
Inside your form.
在你的表格。
#8
0
This answer will show you that how to work in asp.net with razor, and to control multiple submit button event. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
这个答案将向您展示如何使用razor在asp.net中工作,以及如何控制多个提交按钮事件。例如,我们有两个按钮,一个按钮将我们重定向到“PageA”。cshtml”和其他将把我们重定向到“PageB.cshtml”。
@{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
#9
0
In case you're using pure razor, i.e. no MVC controller:
如果你使用纯razor,即没有MVC控制器:
<button name="SubmitForm" value="Hello">Hello</button>
<button name="SubmitForm" value="World">World</button>
@if (IsPost)
{
<p>@Request.Form["SubmitForm"]</p>
}
Clicking each of the buttons should render out Hello and World.
单击每个按钮应该呈现Hello和World。
#10
0
Didn't see an answer using tag helpers (Core MVC), so here it goes (for a delete action):
没有看到使用标记帮助器(核心MVC)的答案,所以在这里(对于删除操作):
On HTML:
HTML:
<form action="" method="post" role="form">
<table>
@for (var i = 0; i < Model.List.Count(); i++)
{
<tr>
<td>@Model.List[i].ItemDescription</td>
<td>
<input type="submit" value="REMOVE" class="btn btn-xs btn-danger"
asp-controller="ControllerName" asp-action="delete" asp-route-idForDeleteItem="@Model.List[i].idForDeleteItem" />
</td>
</tr>
}
</table>
</form>
On Controller:
控制器:
[HttpPost("[action]/{idForDeleteItem}"), ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(long idForDeleteItem)
{
///delete with param id goes here
}
Don't forget to use [Route("[controller]")]
BEFORE the class declaration - on controller.
不要忘记在类声明- on控制器之前使用[Route("[controller])]。
#11
0
Simplest way is to use the html5 FormAction
and FormMethod
最简单的方法是使用html5 FormAction和FormMethod
<input type="submit"
formaction="Save"
formmethod="post"
value="Save" />
<input type="submit"
formaction="SaveForLatter"
formmethod="post"
value="Save For Latter" />
<input type="submit"
formaction="SaveAndPublish"
formmethod="post"
value="Save And Publish" />
[HttpPost]
public ActionResult Save(CustomerViewModel model) {...}
[HttpPost]
public ActionResult SaveForLatter(CustomerViewModel model){...}
[HttpPost]
public ActionResult SaveAndPublish(CustomerViewModel model){...}
There are many other ways which we can use, see this article ASP.Net MVC multiple submit button use in different ways
我们还可以使用许多其他方法,请参阅本文ASP。Net MVC多重提交按钮的使用方式不同
#12
0
This is what worked for me.
这对我起了作用。
formaction="@Url.Action("Edit")"
Snippet :
代码片段:
<input type="submit" formaction="@Url.Action("Edit")" formmethod="post" value="Save" class="btn btn-primary" />
<input type="submit" formaction="@Url.Action("PartialEdit")" formmethod="post" value="Select Type" class="btn btn-primary" />
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit( Quote quote)
{
//code
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PartialEdit(Quote quote)
{
//code
}
Might help some one who wants to have 2 different action methods instead of one method using selectors or using client scripts .
对于那些想要使用两个不同的操作方法而不是使用选择器或使用客户端脚本的方法的人来说,这可能会有所帮助。