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