Home C# Handle Multiple Submit Buttons in Single MVC Form

Handle Multiple Submit Buttons in Single MVC Form

15
0

Now here in this tutorial, I will explain how to handle multiple submit buttons within single form in MVC using c# with example code snippet.

In my previous tutorials, I’d explained deserialize xml document data into list, format json date into local date string, tooltip example to show hide hint or help text using css3 transition and other more cracking tutorials on Asp.net, MVC here.

 

Handle Multiple Submit Buttons within MVC View Form – [.cshtml]

Following is the MVC form which contains two submit buttons:

@using (Html.BeginForm(“Index”, “Home”, FormMethod.Post, new { id = “form1” }))
{
@Html.TextBoxFor(m => m.Name, new { maxlength = 50 })

<input type=”submit” id=”btnSave” name=”command” value=”Save” />
<input type=”submit” id=”btnCancel” name=”command” value=”Cancel” />
}

As you can see from above declaration, I’ve used name=”command” as button property which will later needed to identify the command either Save or Cancel in action method below.

Handle Multiple Submit Buttons – [C#]

Use below method in your .cs page to determine the command name and then perform task according to the button’s command name.

[HttpPost]
public ActionResult Index(StudentModel model, string command)
{
if (command == “Save”)
{
//your “Save” button code here..                                
}
else if (command == “Cancel”)
{
//your “Cancel” button code here..
}

return View(model);
}

We need to add command parameter in ActionResult Index(StudentModel model, string command) action method which is the key to determine the call and depending on that we can perform specific tasks for that command type.

Note: There are many ways to handle multiple submit buttons within single form but I prefer this method because it’s very straight forward and easy to use. Isn’t it? 😉

LEAVE A REPLY

Please enter your comment!
Please enter your name here
Captcha verification failed!
CAPTCHA user score failed. Please contact us!