One main difference I noticed between ViewData and ViewBag is:
ViewData : it will return object does not matter what you have assigned into this and need to typecast again back to the original type.
ViewBag : it is enough smart to return exact type what you have assigned to it it does not matter weather you have assigned simple type (i.e. int, string etc.) or complex type.
Ex: Controller code.
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Products p1 = new Products();
p1.productId = 101;
p1.productName = "Phone";
Products p2 = new Products();
p2.productId = 102;
p2.productName = "laptop";
List<Products> products = new List<Products>();
products.Add(p1);
products.Add(p2);
ViewBag.Countries = products;
return View();
}
}
public class Products
{
public int productId { get; set; }
public string productName { get; set; }
}
}
View Code.
<ul>
@foreach (WebApplication1.Controllers.Products item in ViewBag.Countries)
{
<li>@item.productId @item.productName</li>
}
</ul>
OutPut Screen.