Introduction
In this article we post data from a view to a controller using a form and get the data using Request.Params.
To post data from a view to a controller, we saw the following methods:
- Using Html.BeginForm() View To Controller Method 1.
- Using Html.BeginForm() by passing the action name and controller name explicitly in View To Controller Method 2.
- Using Html.BeginForm() by passing FormMethod View To Controller Method 3.
- Using Html.BeginForm() by calling the action method by action name View To Controller Method 4.
- Using Html.BeginForm() and request object View To Controller Method 5.
- Using the Html form element and request object View To Controller Method 6.
- Using the Html form element and valueprovider View To Controller Method 7.
- Using the Html form element and Request.Form.Get.
Procedure
- Create an MVC project from the "Empty" template.
Right-click on "Controllers" and select "Add" >> "Controller...".
- Select "MVC 5 Controller - Empty" to add an empty controller.
Click on the "Add" button.
- Name the controller "CalcController".
The Index() action result method will be added.
- To add a view, right-click on "Index" and select "Add View...".
- Name the view and select "Empty (without model)" as the template. Click on the "Add" button.
- Create an HTML form element and define input controls inside the form element and set the post method.
- In the controller we get data using the Request object. Request.Params gets a combined collection of Querystring, Form, ServerVariables and Cookies items. Here in our example it gets from Form.
- 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.
<< View to Controller Method 8: Day 30