Adding Dynamic Output in MVC Using ViewBag

Published on Monday, March 19, 2012
mvc

Here is a simple sample for how to add dynamic output in MVC using ViewBag:

In Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            int hour = DateTime.Now.Hour;
            ViewBag.Greeting = hour < 12 ? "Good morning" : "Good afternoon";
            return View();
        }
    }

In View:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<div>
@ViewBag.Greeting, world
</div>