View to Controller Method 1: Day 16

Introduction

This article shows how to pass data from a view to a controller using 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 as "CalcController". The 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

The BeginForm() method writes an opening <form> tag to the response and when we use this method with a "using" block, it will render a closing </form> tag at the end of the using block. The form tag uses the POST method and it calls the action method for the view.

So here we write our code inside a using block. Inside using block in first row we get data from viewdata, sends by controller action method. In the second and third row, we create two textboxes to get user input. In the third row we create submit button to submit the form.

Index Page in MVC

Step 7

Create an action method with a HttpPost attribute. The HttpPost attribute is used to restrict an action method so that the method handles only HTTP POST requests. We define FormCollection in a parameter containing the form value providers for the application. We get the values of two textboxes using a formcollection object. Finally we store the result value in viewdata. When we submit the form, the request will be processed by an action method and action method returns view. And in view we renders the result using viewdata.

Controller in MVC

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.

Accessing Index Page in MVC

Result Page

<< Day 15                                                                                      >> Day 17


Similar Articles