How to pass values from Controller to View using ViewBag in MVC 3

Hello, In this small article I have shown how to pass a value from a Controller to a View using ViewBag.

Below is the code.

Controller code

public class HomeController : Controller  
{  
    //  
    // GET: /Home/
    public ActionResult Index()  
    {  
        ViewBag.Greet = DateTime.Now.Hour < 12 ? "Good Morning" : "Good Afternoon";  
        return View();  
    }
}  

Razor code

@{  
    Layout = null;  
}

<!DOCTYPE html>

<html>  
    <head>  
    <title>Index</title>  
    </head>  
    <body>  
        <div>  
        @ViewBag.Greet, World !  
        </div>  
    </body>  
</html>

Output

Thanks !

About Yasser Shaikh

Hello, I am a Web Dev, employed with Media.Net where I primarily work on ASP.NET MVC and Angular JS based developement.

Questions? Enquiries? Comments? Or even just want to say “Hi” to me, you are welcome to all of that. Just drop me a message at “mail@yassershaikh.com” and I’ll get back to you as soon as possible.

Cheers !

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>