View to Controller Method 4: Day 19

In this article we post data from a view to a controller by calling an action method by action name, not method name.

To post data from a view to a controller, we have seen the following methods:

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 the action name in Html.BeginForm that is defined with the ActionName attribute above the action method in the controller.

action method in controller

Step 7

redefines the name of the method

The ActionName attribute redefines the name of the method. So the view name should be matched with the action name, not the method name. Otherwise you need to return the view with your view name.

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.

Run the project

Output of project
<< View to Controller Method 3: Day 18                        View to Controller Method 5: Day 20>>

Up Next
    Ebook Download
    View all
    Learn
    View all