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.
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.
yes, multiple submit buttons can include in the html form. One simple example is given below.
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.
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.
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 }
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... } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With