Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC razor form with multiple different submit buttons?

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.

like image 429
Toubi Avatar asked Oct 29 '13 05:10

Toubi


People also ask

Can you have multiple submit buttons in a form MVC?

One Form can do a POST submission to one Action method in Controller and hence in order to use multiple Submit buttons inside one single Form, a Switch case has to be implemented inside the Action method.

Can a form have 2 submit buttons?

yes, multiple submit buttons can include in the html form. One simple example is given below.

How do I apply multiple submit buttons in one form?

Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.

Which function is used to handle multiple submit buttons?

Multiple buttons with different names To display a data entry textboxes EditorForModel() helper is used. You can very well use helpers such as TextBoxFor() and LabelFor() if you so wish. There are two submit buttons - one with name attribute set to save and the other with name of cancel.


2 Answers

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 } 
like image 108
Jeroen Doppenberg Avatar answered Sep 19 '22 17:09

Jeroen Doppenberg


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...     } } 
like image 24
Priyank Sheth Avatar answered Sep 21 '22 17:09

Priyank Sheth