C# MVC 提交按钮已被按下

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1714028/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:11:44  来源:igfitidea点击:

MVC which submit button has been pressed

c#asp.netasp.net-mvcrazor

提问by Coppermill

I have two buttons on my MVC form:

我的 MVC 表单上有两个按钮:

<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

From my Controller action how do I know which one have been pressed?

从我的控制器操作中,我如何知道按下了哪个?

采纳答案by WDuffy

Name both your submit buttons the same

将两个提交按钮命名为相同

<input name="submit" type="submit" id="submit" value="Save" />
<input name="submit" type="submit" id="process" value="Process" />

Then in your controller get the value of submit. Only the button clicked will pass its value.

然后在您的控制器中获取提交的值。只有被点击的按钮才会传递它的值。

public ActionResult Index(string submit)
{
    Response.Write(submit);
    return View();
}

You can of course assess that value to perform different operations with a switch block.

您当然可以评估该值以使用 switch 块执行不同的操作。

public ActionResult Index(string submit)
{
    switch (submit)
    {
        case "Save":
            // Do something
            break;
        case "Process":
            // Do something
            break;
        default:
            throw new Exception();
            break;
    }

    return View();
}

回答by Darin Dimitrov

<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

And in your controller action:

在您的控制器操作中:

public ActionResult SomeAction(string submit)
{
    if (!string.IsNullOrEmpty(submit))
    {
        // Save was pressed
    }
    else
    {
        // Process was pressed
    }
}

回答by chugh97

Can you not find out using Request.Form Collection? If process is clicked the request.form["process"] will not be empty

使用 Request.Form Collection 找不到吗?如果单击进程,则 request.form["process"] 不会为空

回答by Yakir Manor

this is a better answer, so we can have both text and value for a button:

这是一个更好的答案,因此我们可以同时拥有按钮的文本和值:

http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx

http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx

</p>
<button name="button" value="register">Register</button>
<button name="button" value="cancel">Cancel</button>
</p>

and the controller:

和控制器:

public ActionResult Register(string button, string userName, string email, string password, string confirmPassword)
{
if (button == "cancel")
    return RedirectToAction("Index", "Home");
...

in short its a SUBMIT button but you choose the name using the name attribute, its even more powerful because your not obligated to the name submit or button in the controller method parameters, you can call it as you like...

简而言之,它是一个提交按钮,但您使用 name 属性选择名称,它更强大,因为您不必在控制器方法参数中指定名称提交或按钮,您可以随意调用它...

回答by Owen

Here's a really nice and simple way of doing it with really easy to follow instructions using a custom MultiButtonAttribute:

这是一个非常好的和简单的方法,使用自定义 MultiButtonAttribute 非常容易按照说明进行操作:

http://blog.maartenballiauw.be/post/2009/11/26/Supporting-multiple-submit-buttons-on-an-ASPNET-MVC-view.aspx

http://blog.maartenballiauw.be/post/2009/11/26/Supporting-multiple-submit-buttons-on-an-ASPNET-MVC-view.aspx

To summarise, make your submit buttons like this:

总而言之,让你的提交按钮像这样:

<input type="submit" value="Cancel" name="action" />
<input type="submit" value="Create" name="action" /> 

Your actions like this:

你的动作是这样的:

[HttpPost]
[MultiButton(MatchFormKey="action", MatchFormValue="Cancel")]
public ActionResult Cancel()
{
    return Content("Cancel clicked");
}

[HttpPost]
[MultiButton(MatchFormKey = "action", MatchFormValue = "Create")]
public ActionResult Create(Person person)
{
    return Content("Create clicked");
} 

And create this class:

并创建这个类:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
    public string MatchFormKey { get; set; }
    public string MatchFormValue { get; set; }

    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        return controllerContext.HttpContext.Request[MatchFormKey] != null &&
            controllerContext.HttpContext.Request[MatchFormKey] == MatchFormValue;
    }
}

回答by AAAA

This post is not going to answer to Coppermill, because he have been answered long time ago. My post will be helpful for who will seeking for solution like this. First of all , I have to say " WDuffy's solution is totally correct" and it works fine, but my solution (not actually mine) will be used in other elements and it makes the presentation layer more independent from controller (because your controller depend on "value" which is used for showing label of the button, this feature is important for other languages.).

这个帖子不打算回答Coppermill,因为他早就回答了。我的帖子将对寻求此类解决方案的人有所帮助。首先,我不得不说“WDuffy 的解决方案是完全正确的”并且它工作正常,但我的解决方案(实际上不是我的)将用于其他元素,它使表示层更独立于控制器(因为您的控制器依赖于用于显示按钮标签的“值”,此功能对于其他语言很重要。)。

Here is my solution, give them different names:

这是我的解决方案,给他们不同的名字:

<input type="submit" name="buttonSave" value="Save"/>
<input type="submit" name="buttonProcess" value="Process"/>
<input type="submit" name="buttonCancel" value="Cancel"/>

And you must specify the names of buttons as arguments in the action like below:

并且您必须将按钮的名称指定为操作中的参数,如下所示:

public ActionResult Register(string buttonSave, string buttonProcess, string buttonCancel)
{
    if (buttonSave!= null)
    {
        //save is pressed
    }
    if (buttonProcess!= null)
    {
        //Process is pressed
    }
    if (buttonCancel!= null)
    {
        //Cancel is pressed
    }
}

when user submits the page using one of the buttons, only one of the arguments will have value. I guess this will be helpful for others.

当用户使用其中一个按钮提交页面时,只有其中一个参数具有值。我想这对其他人有帮助。

Update

更新

This answer is quite old and I actually reconsider my opinion . maybe above solution is good for situation which passing parameter to model's properties. don't bother yourselves and take best solution for your project.

这个答案很旧,我实际上重新考虑了我的意见。也许上述解决方案适用于将参数传递给模型属性的情况。不要打扰自己,并为您的项目采取最佳解决方案。

回答by Zonke-Bonke S'cekeleshe Msibi

To make it easier I will say you can change your buttons to the following:

为了方便起见,我会说您可以将按钮更改为以下内容:

<input name="btnSubmit" type="submit" value="Save" />
<input name="btnProcess" type="submit" value="Process" />

Your controller:

您的控制器:

public ActionResult Create(string btnSubmit, string btnProcess)
{
    if(btnSubmit != null)
       // do something for the Button btnSubmit
    else 
       // do something for the Button btnProcess
}

回答by Fredrik Stigsson

// Buttons
<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

// Controller
[HttpPost]
public ActionResult index(FormCollection collection)
{
    string submitType = "unknown";

    if(collection["submit"] != null)
    {
        submitType = "submit";
    }
    else if (collection["process"] != null)
    {
        submitType = "process";
    }

} // End of the index method

回答by Kinjal Gohil

you can identify your button from there name tag like below, You need to check like this in you controller

您可以从下面的名称标签中识别您的按钮,您需要在控制器中像这样检查

if (Request.Form["submit"] != null)
{
//Write your code here
}
else if (Request.Form["process"] != null)
{
//Write your code here
}

回答by Aniket Sharma

Give the name to both of the buttons and Get the check the value from form.

为两个按钮命名并从表单中获取检查值。

<div>
   <input name="submitButton" type="submit" value="Register" />
</div>

<div>
   <input name="cancelButton" type="submit" value="Cancel" />
</div>

On controller side :

在控制器端:

public ActionResult Save(FormCollection form)
{
 if (this.httpContext.Request.Form["cancelButton"] !=null)
 {
   // return to the action;
 }

else if(this.httpContext.Request.Form["submitButton"] !=null)
 {
   // save the oprtation and retrun to the action;
 }
}