Article

Passing Data From Controller To View With ViewBag in MVC

In this blog we will learn Passing Data From Controller To View With ViewBag in MVC.

For now, understand that, ViewBag  is a mechanism to pass data from the controller to the view.

Notes:

To pass data from controller to a view, It’s always a good practice to use strongly typed view models instead of using ViewBag & ViewData.

Write this code on “HomeController.cs” page for Passing Data From Controller To View With ViewBag in MVC.

 

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

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

Now let’s add a View to our project.

1. Right click on the Index() function
2. Click on “Add View”
3. Notice that, the view name in “Add View” dialog box matches the name of the controller action method
4. Select “Razor” as the view engine
5. Leave the rest of the defaults as is, and click “Add” button

Please write this code on Index.cshtml page.

@{
ViewBag.Title = "Countries List";
}

<h2>Countries List</h2>
<ul>
@foreach (string strCountry in ViewBag.Countries)
{
<li>@strCountry</li>

}
</ul>

Please look have screenshot.

 

Tagged

Leave a Reply

Your email address will not be published.