Creating Views in MVC

Views are an important part of an ASP.NET MVC application - they enable you to separate presentation (User Interface) from the logic in your application.

The purpose of a View is render the data and present to the end user.

For creating view in your project, right-click inside the Index method and click Add View.

The Add View dialog box will appears. Leave the defaults entries in the dialog box and click the Add button:

add view dialog

The following Index.cshtml file will be created.

Index.cshtml file

@{
        ViewBag.Title = "Index";
}
<h2>Index</h2>


Notice at the solution explorer View folder. Within the View folder, Home folder is created and Index.cshtml file is present in this Home folder. Because we have already created HomeController (refer "MVC Environment Set Up") and keep in mind that, in the controller more than one Action method may be present.

Let us do one example and create view that will display the list of country. In this example we want to display the list of countries. So We have to create a controller and View. In the HomeController class Index method returns the view. We can use ViewBag and ViewData object to pass the data from controller to View. Please keep in mind that to pass data from controller to view, always try to use strongly typed view model.

HomeController.cs file

using System.Collections.Generic;
using System.Web.Mvc;

namespace MVCDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Countries = new List<string>()
            {
                "India",
                "Canada",
                "Germany",
                "US",
                "England"
            };
            return View();
        }
    }
}


In the above code countries is the name of dynamic property. It means it is created at runtime. The Index method returns the view object. So which view it returns? It returns view that is available in Index.cshtml file. Therefore look at Index.cshtml file given below.

Index.cshtml file

@{
    ViewBag.Title = "Index";
}
<h2> List Of Countries</h2>
<ul>
    @foreach (string strCon in ViewBag.Countries)
    {
       <li>@strCon</li>
    }
</ul>


The @ sign is used in Razor view engine to render the value of variables, expressions and statements to the browser. It is also used to open a code block.

Run the project you will see the following output:

countries list

Important things about ViewBag, ViewData and TempData

In ASP.NET MVC you can use ViewData, ViewBag and TempData for passing data from controller to view.

  • ViewData and ViewBag are properties of ControllerBase class.
  • ViewData is a dictionary of objects
  • ViewBag is a dynamic property.
  • ViewData requires typecasting for complex data type and check for null values to avoid error.
  • ViewBag doesn’t require typecasting for complex data type.
  • ViewData is accessible using strings as keys.
  • TempData is also a dictionary object that is derived from TempDataDictionary class
  • Tempdata helps to maintain data when you move from one controller to other controller or from one action to other action.
  • TempData internally uses session variables.
Example:
ViewData[“keyName”]=”SomeData”;
ViewBag.PropertyName=”SomeData”;


ViewData and ViewBag object does not support compile time error. Suppose that you have wrongly written the property name or key name, then it will not give you compile time error. You will get the error at run time. So always try to use strongly typed data model.
Let us see how we can use ViewData object instead of ViewBag. Change the code in controller as given below.

public ActionResult Index()
{
        ViewData["CountryList"] = new List<string>()
        {
              "India",
              "Canada",
              "Germany",
              "US",
              "England"
         };
         return View();
}

Update the code in view as

<ul>
    @foreach (string strCon in (List<string>) ViewData["CountryList"])
    {
       <li>@strCon</li>
    }
</ul>