Monday, September 26, 2016

How to Handle Multiple Submit Buttons in Single MVC Form?

MVC View Form – [.cshtml]

Following is the MVC form which contains two submit buttons:
 
  1. @using (Html.BeginForm("Index""Home", FormMethod.Post, new { id = "form1" }))  
  2. {  
  3. @Html.TextBoxFor(m => m.Name, new { maxlength = 50 })  
  4. <input type="submit" id="btnSubmit" name="command" value="Submit" />  
  5. <input type="submit" id="btnReset" name="command" value="Reset" />  
  6. }  
I have used name=”command” as button property which will later needed to identify the command either Submit or Reset in action method below.
 
Below method in your .cs page to determine the command name and then perform task according to the button’s command name. 
 
  1. [HttpPost]  
  2. public ActionResult Index(StudentModel model, string command)  
  3. {  
  4.        if (command == "Submit")  
  5.        {  
  6.                //your "Submit" button code here..                                  
  7.        }  
  8.        else if (command == "Reset")  
  9.        {  
  10.                //your "Reset" button code here..  
  11.        }  
  12.        return View(model);  
  13. }  
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. 

No comments:

Post a Comment