How To Use Multiple Buttons on Single View In ASP.NET MVC

There are many scenarios where we need multiple submit buttons on single view but in this example we are considering the scenario in which we have one view from where the user can add the employee details and if the details are not sufficient then the user can save it as a draft. Now let's start creating a simple MVC application to demonstrate the above scenario.
Step 1: Create an MVC Application.

Now let us start with a step by step approach from the creation of a simple MVC application as in the following,
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear,

Step 2: Create Model Class

Now let us create the model class file named EmployeeModel.cs by right clicking on model folder as in the following screenshot,

Note

It is not mandatory that Model class should be in Models folder, it is just for better readability; you can create this class anywhere in the solution explorer. This can be done by creating different folder names or without folder name or in a separate class library.

EmployeeModel.cs class file code snippet
using System.ComponentModel.DataAnnotations;  
  
namespace ManagningMultipleSubmitButtonsInMVC.Models  
{  
    public class EmployeeModel  
    {  
        [Required]  
        public string Name { get; set; }  
        [Required]  
        public string City { get; set; }  
       
        public string Address { get; set; }  
    }  
}  
Step 3: Add Controller Class

Now let us add the MVC 5 controller as in the following screenshot,

After clicking on Add button it will show the window. Specify the Controller name as Home with suffix Controller.
Note

The controller name must have a suffix as 'Controller' after specifying the name of the controller. Now modify the default code in HomeController.cs class file and create two action methods, after modifying the code will look like as follows,
HomeController.cs
using ManagningMultipleSubmitButtonsInMVC.Models;  
using System.Web.Mvc;  
  
namespace ManagningMultipleSubmitButtonsInMVC.Controllers  
{  
    public class HomeController : Controller  
    {  
          
        public ActionResult Employee()  
        {  
            return View();  
        }  
        [HttpPost]  
        public ActionResult Save(EmployeeModel objSave)  
        {  
  
            ViewBag.Msg = "Details saved successfully.";  
            return View();  
        }  
        [HttpPost]  
        public ActionResult Draft(EmployeeModel objDraft)  
        {  
            ViewBag.Msg = "Details saved as draft.";  
            return View();  
        }  
  
    }  
}  
In the preceding code sample, we have two action methods named Save and Draft Save action method is used to save the records and Draft is used to save the details as draft for saving later.

Step 4: Create View

Now let's create strongly typed view named Employee from EmployeeModel class ,

Click on Add button then it will create the view named Employee, Now open the Employee.cshtml view, then some default code you will see which is generated by MVC scaffolding template, now modify default code to make as per our requirements. After modifying the code it will look like as in the following,
@model ManagningMultipleSubmitButtonsInMVC.Models.EmployeeModel  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
@using (Html.BeginForm())   
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">  
          
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-12">  
                <input type="submit" value="Save" class="btn btn-primary" />  
                <input type="submit" value="Draft" class="btn btn-primary" />  
  
            </div>  
              
        </div>  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
               @ViewBag.Msg  
  
            </div>  
  
        </div>  
    </div>  
}  
<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
<script src="~/Scripts/jquery.validate.min.js"></script>  
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 
Now after adding the Model, add View and controller into our project. The solution explorer will look like as follows,

Step 5 : Now run the application and click on any one of the buttons,  it will fire only Save action method as,

In the preceding screen shot, if we clicked on any one of the buttons it will point to the save action method because we have only one form and two submit buttons, so it's not possible to point to two different buttons on two different action methods usingthe preceding scenario.

Step 6 :Solution

There are lots of solutions to solve the preceding issue, we will look at the one which requires the least effort to solve the same scenario:
  • By creating two forms on single view by using html.Action helper class
  • By changing input type submit button of those submit buttons but the model validation will not be fired .
  • By Using javascript or jQuery to submit forms but default validations will not work.
  • By using action name along with name property in submit button.
  • By Using formaction property of submit button,
So in this article we will use a simple way by formation of name property of submit button:

In the preceding example we have provided the ActionResult method name in formation property of submit button, now let's update the Employee.cshtml view code; after updating the code; the Employee.cshtml code will look like as follows
@model ManagningMultipleSubmitButtonsInMVC.Models.EmployeeModel  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
@using (Html.BeginForm("Save","Home",FormMethod.Post))   
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">  
          
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-12">  
  
  
                <input type="submit" value="Save" formaction="Save"  class="btn btn-primary" />  
  
                <input type="submit" value="Draft"  formaction="Draft" class="btn btn-primary" />  
  
            </div>  
              
        </div>  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10 text-success">  
                @ViewBag.Msg  
                
  
            </div>  
  
        </div>  
    </div>  
}  
<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
<script src="~/Scripts/jquery.validate.min.js"></script>  
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Step 7: Now let's run the application and click on the save button, then it will fire the save action method as,

Now click on draft button, it will fire the Draft action method and  show the following message,
 I hope from all the preceding examples we have learned how to use multiple submit buttons on single view in ASP.NET MVC.
Note
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
Summary
I hope this article is useful for all readers. If you have any suggestions please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode