- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use ViewBag in ASP .Net MVC C#?
ViewBag uses the dynamic feature that was introduced in to C# 4.0. It allows an object to have properties dynamically added to it. Internally, it is a dynamic type property of the ControllerBase class which is the base class of the Controller class.
ViewBag only transfers data from controller to view, not visa-versa. ViewBag values will be null if redirection occurs. ViewBag is able to set and get value dynamically and able to add any number of additional fields without converting it to strongly typed.
Storing data in ViewBag −
ViewBag.Counties = countriesList;
Retrieving data from ViewBag −
string country = ViewBag.Countries;
Controller
Example
using System.Collections.Generic; using System.Web.Mvc; namespace DemoMvcApplication.Controllers{ public class HomeController : Controller{ public ViewResult Index(){ ViewBag.Countries = new List<string>{ "India", "Malaysia", "Dubai", "USA", "UK" }; return View(); } } }
View
@{ ViewBag.Title = "Countries List"; } <h2>Countries List</h2> <ul> @foreach(string country in ViewBag.Countries){ <li>@country</li> } </ul>
Output
- Related Articles
- What is ViewData in ASP .Net MVC C#?
- What is the use of ChildActionOnly attribute in ASP .Net MVC C#?
- What is the significance of NonActionAttribute in ASP .Net MVC C#?
- How can we provide an alias name for an action method in Asp .Net MVC C#?
- What are the levels at which filters can be applied in ASP .Net MVC C#?
- What are the three segments of the default route, that is present in ASP .Net MVC C#?
- How to get formatted JSON in .NET using C#?
- How to determine if C# .NET Core is installed?
- How can we get the client's IP address in ASP.NET MVC C#?
- With use of SAP .NET Connector to perform an upgrade
- Explain the MVC pattern in ASP.NET
- How to calculate net present value using Net present value (NPV)?
- Upgrading SAP .NET Connector from .NET 2.0 to .NET 3.0
- Difference between JSP and ASP
- Difference Between HTML and ASP.

Advertisements