This article describes ViewData in MVC. Viewdata maintains data when you move from a controller to a view.
IntroductionThis series contains step-by-step MVC samples for absolute beginners. It covers only the practical implementations of MVC concepts.Let's start with the viewdata. Viewdata maintains data when you move from a controller to a view.Step 1Click on the "Start" Button then expand "Visual Studio 2013" and click on "Visual Studio 2013".It will open the Start Page of "Visual Studio 2013".Step 2Go to the "File" menu then expand "New" and click on "Project…".Step 3Select "Visual C#" on the left and then select "Web" and select "ASP.NET Web Application" on the center then name the project and select your desired location.Step 4Select the "Empty" template then check "MVC" from "Add folders and core references for:".Step 5Right-click on "Controllers" and select "Add" >> "Controller…".Step 6Select "MVC 5 Controller - Empty" to add an empty controller then click on the "Add" button.Step 7Name the controller.Step 8This will add an empty controller inside the "Controllers" folder. The Controller has one Action method and action methods typically return a result that is known as an "ActionResult". ActionResult represents a result of an action method. Here the action result returns a View method.To pass the value from the controller to the view we need to store a value in the ViewData inside the controller. Here we store a datetime value in the ViewData. Find the syntax of viewdata in the following screen.Step 9Now we need to create a view. Right-click on "Index" and select "Add View…".Step 10For now do not change the view name. The Action method name and view name should be the same. Select "Empty (without model)" as the template and click on the "Add" button.Step 11The Index.cshtml file is created under the Views >> Home. We are using the view-engine option called "Razor". So we use rezor's @ and then syntax to get data from ViewData.Please refer to the following screen shot for the entire syntax.Step 12Run the project and you will get the current datetime on the browser using ViewData.ViewData is one of the ways to transfer data from a controller to a view.>> Day 2
ASP.NET MVC 5: A Beginner’s Guide