71

A Razor view has 3 buttons inside a form. All button's actions will need form values which are basically values coming input fields.

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
Toubi
  • 2,469
  • 10
  • 33
  • 49
  • show us some code please... what have you tried? probably, from the question `jquery` might come in handy for you.. – now he who must not be named. Oct 29 '13 at 05:43
  • Its not directly possible to do what you have asked, but with a workaround, check [this link](http://stackoverflow.com/a/19272670/2121389) – AthibaN Oct 29 '13 at 05:55
  • please show us your snippet – Lamloumi Afif Oct 29 '13 at 08:20
  • Possible duplicate of [How do you handle multiple submit buttons in ASP.NET MVC Framework?](http://stackoverflow.com/questions/442704/how-do-you-handle-multiple-submit-buttons-in-asp-net-mvc-framework) – KyleMit Jul 13 '16 at 15:17
  • this kind of question has been asked before.. one of my answer is over here [Multiple submit buttons in mvc](http://stackoverflow.com/a/41285321/7015584) .. hope it helps.. – Jeff D Dec 22 '16 at 15:14

14 Answers14

104

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
}
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Jeroen Doppenberg
  • 1,558
  • 1
  • 10
  • 13
93

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...
    }
}
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
Priyank Sheth
  • 2,352
  • 19
  • 32
  • 5
    This is brilliant! Wish I could've given you so many more upvotes! – SNag Jul 01 '15 at 01:19
  • @PaulZahra: This is mine one which I use. I don't need to cut-down your solution in order to post or repost it again. Please remove down-vote right now. – Priyank Sheth Jan 25 '16 at 10:42
  • 1
    @SimpleMan I am not claiming copyright over a solution... I didn't mean to imply you did a copy and paste exercise... the point I was trying to make is that it is in fact a duplicate answer of what I posted 14 mins earlier... and as such I downvoted it... isn't that fair? – Paul Zahra Jan 25 '16 at 10:59
  • @PaulZahra I don't think so its duplicate. So many folks post same anser in matter of few minutes or hours. So does that mean that they deserve down-vote? Do you think that is good for anyone? Have you compared our answers line by line? Where did you found duplication? Please justify it properly. – Priyank Sheth Jan 27 '16 at 03:46
  • I am not going to edit my answer as I don't consider it as duplicate of yours. If I didn't do it at all, then why I should edit my answer? – Priyank Sheth Jan 29 '16 at 06:51
  • @JeremyThompson Thx, sorted. – Paul Zahra Feb 02 '16 at 09:06
  • @PriyankSheth multiple people can independently write similar code, especially for something like "multiple submit buttons on a form." – Phillip Copley Mar 30 '17 at 18:57
  • @PhillipCopley: In what context you are commenting at this point of time? Please elaborate. – Priyank Sheth Apr 24 '17 at 05:07
18

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"){


}
Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191
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:

 <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):

<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):

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) {

        }
    });
};
tristanm
  • 3,337
  • 2
  • 27
  • 40
Arthur
  • 1,740
  • 3
  • 16
  • 36
5

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 .

user2695433
  • 2,013
  • 4
  • 25
  • 44
  • 1
    How would you use this with Razor Pages without MVC? The formaction keeps taking me to the default form action "Course". When I want to go to "Courses_Temp"? – JustJohn Jun 15 '19 at 20:12
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();
    }
Paul Zahra
  • 9,522
  • 8
  • 54
  • 76
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" />
  }
TK-421
  • 387
  • 2
  • 11
  • 3
    What if i need the form values for both buttons but I take different actions like edit or delete – Chad Aug 15 '14 at 16:40
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) .

@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.

galmeida
  • 221
  • 2
  • 10
  • 1
    While the chosen answer and most of the other ones are functional, I'd rather choose this answer 'cause it beautifully keeps roles separated. Controllers shouldn't be modified for this kind of UI changes (provided you already have the controller logic ready). As such, using javascript keeps the changes where they belong: UI only. – Charles Roberto Canato Dec 21 '15 at 17:12
3

Simplest way is to use the html5 FormAction and 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

Ali Adravi
  • 21,707
  • 9
  • 87
  • 85
2

As well as @Pablo's answer, for newer versions you can also use the asp-page-handler tag helper.

In the page:

<button asp-page-handler="Action1" type="submit">Action 1</button>
<button asp-page-handler="Action2" type="submit">Action 2</button>

then in the controller:

    public async Task OnPostAction1Async() {...}
    public async Task OnPostAction2Async() {...}
Andy
  • 10,412
  • 13
  • 70
  • 95
1

Didn't see an answer using tag helpers (Core MVC), so here it goes (for a delete action):

On 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.

Pablo
  • 361
  • 3
  • 6
1

Information acquired from: http://www.codedigest.com/posts/46/multiple-submit-button-in-a-single-form-in-aspnet-mvc

For you chaps coming more recently, you can use the HTML 5 Formaction Attribute.

In your <input> or <button>

Just define:

<button id="btnPatientSubmit" type="submit" class="btn btn-labeled btn-success" formaction="Edit" formmethod="post">

Notice the addition of formation= "Edit", this specifies which ActionResult I want to submit to in my controller.

This will allow you to have multiple submit buttons, where each could submit to independent ActionResults (Methods) in your controller.

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".

@{
  if (IsPost)
    {
       if(Request["btn"].Equals("button_A"))
        {
          Response.Redirect("PageA.cshtml");
        }
      if(Request[&quot;btn"].Equals("button_B"))
        {
          Response.Redirect(&quot;PageB.cshtml&quot;);
        }
  }
}
<form method="post">
   <input type="submit" value="button_A" name="btn"/>;
   <input type="submit" value="button_B" name="btn"/>;          
</form>

Pir Fahim Shah
  • 10,505
  • 1
  • 82
  • 81
0

In case you're using pure razor, i.e. no MVC controller:

<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.

Jacques
  • 6,936
  • 8
  • 43
  • 102
  • But this doesn't submit the form. Or am I wrong? How would you call a whole different Page with a button besides the default form action for 1st button? – JustJohn Jun 15 '19 at 20:03