Controller to Controller Sample in MVC: Day 34

Introduction

In this sample example we send some value from one controller to another controller.

We use TempData to store temporary data in a dictionary and the RedirectToAction method to redirect to the specified action using the action name and controller name. TempData keeps the information during the HttpRequest. It is used to maintain data from one controller to another controller, in other words during redirects. So in our example we store the session id in TempData and in the next step we use the RedirectToAction method with index as the action name and the second is the controller name; that means that we call the Index method of the second controller.

Now let's see the step-by-step implementation:

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

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

  3. Name the controller "CalcController". The Index() action result method will be added.

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

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

  6. Now add one more controller. Right-click on "Controllers" and select "Add" >> "Controller...".

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

  8. Name the controller "CalcController". The Index() action result method will be added.

  9. Store the session id in TempData and the RedirectToAction method will call the index method of the second controller. The first parameter is the action name and the second parameter is the controller name.

    controller

  10. In the second controller get the data from TempData and store it in a string variable.

    another controller

  11. Debug the project and you will see the session id in the first controller.

    session

  12. Now continue debugging and you will get the same session id in the second controller.

    another session

<< Multiple Form Tag Sample in MVC: Day 33


Similar Articles