MVC Sample Application - Part7

        In previous chapter we created a View.Now we will look to work with Controller and View closely.

      Now change the View Code like following and run the application.Changed code highlighted in blue color.


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
         Hello MVC.
    </div>
</body>
</html>

        After running the application we will get a output like following.

Output From View

        The Output generated above is a HTML data.But it is a static data from View.The Index method in Controller code will instruct MVC to render a Index.cshtml using naming conventions.We will learn Routing and naming conventions in later chapters.

        Now we will generate a dynamic output from controller and pass it to the View to display it.
Now change the Controller coding like following.


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

namespace FirstMVCApplication.Controllers
{
    public class FirstController : Controller
    {
        //
        // GET: /First/
        public ActionResult Index()
        {
            DateTime current = DateTime.Now;
            ViewBag.ToDay = "The date and time now is " + current;
            return View();
        }
     }
}

        Now to render a controller data to View we are going to add ViewBag in View like following.

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
         @ViewBag.Today
    </div>
</body>
</html>

           Now run the application and we will get a output of current date and time like following.

Output from ViewBag


            Here we used ViewBag to carry information from controller side to View.In controller we assigned current date time to ViewBag with some name(ViewBag.Today) and same is used in View by using @ViewBag.Today.

             ASP.NET MVC offers us three options - ViewDataViewBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility.We will learn about these in later chapters.