Home C# Handle Multiple Submit Buttons in Single MVC Form

Handle Multiple Submit Buttons in Single MVC Form

38
0
Handle Multiple Submit Buttons in Single MVC Form
Handle Multiple Submit Buttons in Single MVC Form

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? ๐Ÿ˜‰
Previous articleDeserialize XML Document Data and Convert into .Net Array List
Next articleGet Hash Value From Current Page URL In jQuery
Hi there, I am Mayank, the man behind Technical Mack. I started AspnetO with a motive to educate people on various programming languages ranging from beginners to expert level. Through this blog, I aim to provide more insightful content.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

twelve − 5 =