View to Controller Method 3: Day 18

Introduction

This article shows how to pass data from a view to a controller using:

Html.BeginForm(HtmlHelper, String, String, FormMethod)

In order to post data from a view to the controller, so far we have seen the following two methods:

  1. Using Html.BeginForm() View To Controller Method 1
  2. Using Html.BeginForm() by passing action name and controller name explicitly View To Controller Method 2
In method 3 we pass "FormMethod" inside Html.BeginForm().

Step 1

    Create a MVC project from the "Empty" template. Right-click on "Controllers" and select "Add" >> "Controller...".

Step 2

    Select "MVC 5 Controller - Empty" to add an empty controller. Click on the "Add" button.

Step 3

    Name the controller "CalcController"; an Index() action result method will be added.

Step 4

    To add a view, right-click on "Index" and select "Add View...".

Step 5

    Name the view and select "Empty (without model)" as the template. Click on the "Add" button.

Step 6

    Pass FormMethod inside Html.BeginForm(). FormMethod represents the HTTP method for processing the form, either GET or POST. So far we attach a HttpPost attribute to the action method in the controller.

    Html Begin Form

Step 7

    Create an action method with the name "Add" and when the view is returned, pass the view name "Index" as the parameter.

    Here there is no need to add an attribute "HttpPost" since it is added in html.beginform.

    HTML BeginForm Method

Step 8

    Run the project, insert a value for no1 and no2 and click on the "Submit" button. The form will be submitted and we will get the sum of the two values.

    Example of Controller Method

    output of Controller Method

In future articles we will see four more methods to post data using the same example. There is no major differences or say Rocket Science but the intent is to be aware for doing the same thing with various approaches.
I hope you enjoy reading this series!

Up Next
    Ebook Download
    View all
    Learn
    View all