Multiple Submit Button in a Single Form – ASP.NET CORE

In this tutorial you will learn

  • How to add multiple submit button in single form?
  • How to bind each button with unique method?

Till now, you learned how to add view and controller in ASP.NET CORE application. You also learned how to get user input using simple form and process the input. In this chapter I am going to explain very important topic that will be very helpful for you when you’ll develop real project. This topic is implementation of multiple submit button in a single form. To demonstrate it well I have designed a calculator app that will receive 2 inputs from the user and returns result according to button click. So, let’s start a new calculator app in ASP.NET CORE.

1. Create New ASP.NET Core Project Calculator. Open Visual Studio 2015 and go to File New Project.


2. Select Web in left side and then select ASP.NET Core Web Application (.Net Core). Enter your Project Name Calculator in the Name field and click OK.


3. A template window will open. Choose Web Application in template section and set Authentication to No Authentication.


4. Now your project is opened. Create a View Page CalPage.cshtml in MyCal folder. However, you are free to choose your name. Right click on Views Add New Folder. Rename this folder to MyCal.


5. Now right click on MyCal folder add New Item. Select MVC View Page in ASP.NET section and rename it CalPage.cshtml.


6. Open CalPage.cshtml and paste the following code.

  •  

    Explanation

    <input type="submit" value="+" formaction="Add" />
     
    The only noticeable thing is that formaction properties of submit button. This property allows button to execute separate function.

    7. Create New Controller. Right click on Controllers Add New Item. Select MVC Controller Class and rename it MyCalController.cs and click Add button.


    8. Now open MyCalController.cs and paste following codes.

    Explanation

    1. Here, I created 4 different types of functions Add(), Minus(), Multiply() and Divide().
    2. I also used try catch exception handling because I don’t want to get any exception on the page. I am not verifying user input here because my motive is to teach you how to operate multiple submit button in a form.
    3. Process is very simple. Received input from textboxes, processed input and return result along with correct view page.
    9. Press Ctrl + F5 to Run your project. Add /MyCal/CalPage at the end of URL and press Enter. Ex.


    10. Now, you can input the integer and test your project.


    Summary

    In this chapter you learned how to implement multiple submit button in a single form in ASP.NET Core. After completing this chapter, now you have better understanding of Controller. Now, you are ready to learn Model in ASP.NET Core.


    Leave a Reply

    Your email address will not be published. Required fields are marked *