C# 具有多个不同提交按钮的 MVC 剃刀表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19650345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC razor form with multiple different submit buttons?
提问by Toubi
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.
我非常感谢您的时间、指导和帮助。
采纳答案by Jeroen Doppenberg
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
}
回答by Arthur
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) {
}
});
};
回答by Lamloumi Afif
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"){
}
回答by TK-421
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" />
}
回答by Pir Fahim Shah
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>
回答by Paul Zahra
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();
}
回答by learner
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.
并在您的控制器的 action 方法中接受它作为参数。
public ActionResult Create(Employee model, string command)
{
if(command.Equals("submit1"))
{
// Call action here...
}
else
{
// Call another action here...
}
}
回答by galmeida
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 文件夹中创建一个文件“Helper.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.
在你的表格里面。
回答by Jacques
In case you're using pure razor, i.e. no MVC controller:
如果您使用的是纯剃刀,即没有 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。
回答by Pablo
Didn't see an answer using tag helpers (Core MVC), so here it goes (for a delete action):
没有看到使用标签助手(Core 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.
不要忘记[Route("[controller]")]
在类声明之前使用- 在控制器上。