View to Controller Method 7: Day 22

Introduction

In this article we post data from a view to a controller using a form and get the data using a value provider.
To post data from a view to a controller, we saw the following 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
  3. Using Html.BeginForm() by passing FormMethod View To Controller Method 3
  4. Using Html.BeginForm() by calling action method by action name View To Controller Method 4
  5. Using Html.BeginForm() and request object View To Controller Method 5
  6. Using Html form element and request object View To Controller Method 6

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".

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.

set post method in HTML

Step 6

Create a HTML form element and define input controls inside the form element and set post method.

Step 7

Valueprovider gets or sets the value provider for the controller. Getvalue retrieves a value object using the specified key and key is of the value object to retrieve. Attemptedvalue gets or sets a rawvalue that is converted to a string for display. You can use ValueProvider.GetValue(“key”).RawValue but we need to consider that it is not always a string.

controler in c sharp

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.

input value

output result

<< View to Controller Method 6: Day 21                     Error Handling Method 1: Day 1 of 23 >>     

Up Next
    Ebook Download
    View all
    Learn
    View all