TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

ASP.Net MVC ViewBag

ASP.Net MVC ViewBag with asp.net tutorial, asp.net introduction, features, project, example, server controls, labels, textbox, button, hyperlink, radiobutton, calender, checkbox, fileupload, events handling, authentication, webforms model binding, html server control, compare validdator, range validator, validation summary, mvc introduction, mvc project, view, validation, entity framework, authentication etc.

<< Back to ASP

ASP.NET MVC ViewData, ViewBag and TempData

ASP.NET MVC provides three variables to store and passing values from controller to view. Both ViewData and ViewBag are similar except TempData that has additional features.

We will discuss about each of these with example.


ASP.NET MVC ViewData

It is a dictionary of objects and derived from ViewDataDictionary class. We can access value by using string as a key. It is type-safe and requires typecasting for data type. It avoids error and check for null reference at run time. It is accessible only during current request.

Example

We are creating a controller and returning a view to the browser. This controller passes Courses ViewData to the view.

Controller

using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace ViewBagExample.Controllers
{
    public class ViewBagController : Controller
    {
        // GET: ViewBag
        public ActionResult Index()
        {
            List Courses = new List();
            Courses.Add("J2SE");
            Courses.Add("J2EE");
            Courses.Add("Spring");
            Courses.Add("Hibernates");
            ViewData["Courses"] = Courses;
            return View();
        }
    }
}

View

// Index.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h2>List of Courses</h2>
    <ul>
        @{
            foreach (var Courses in ViewData["Courses"] as List<string>)
            {
                <li> @Courses</li>
            }
        }
    </ul>
</body>
</html>

Output:

It produces the following output to the browser.

ASP View bag 1

ASP.NET MVC ViewBag

It is a dynamic property which is similar to ViewData. It was introduced in .NET Framework version 4.0. it is used to send data from controller to the view page. ViewBag can get and set value dynamically that's why it is called dynamic property. It does not require type conversion and convert type dynamically.

Example

Here, in this example, we are implementing ViewBag property. Controller and an Index file is given below.

Controller

using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace ViewBagExample.Controllers
{
    public class ViewBagController : Controller
    {
        // GET: ViewBag
        public ActionResult Index()
        {
            List<string> Courses = new List<string>();
            Courses.Add("J2SE");
            Courses.Add("J2EE");
            Courses.Add("Spring");
            Courses.Add("Hibernates");
            ViewBag.Courses = Courses;
            return View();
        }
    }
}

View

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h2>List of Courses</h2>
    <ul>
        @{
            foreach (var Courses in ViewBag.Courses)
            {
                <li> @Courses</li>
            }
        }
    </ul>
</body>
</html>

Output:

The Index file produces the following output to the browser.

ASP View bag 2

ASP.NET MVC TempData

It represents a set of data that persists only from one request to the next. It is derived from TempDataDictionary, we can use its object to pass data as we did in ViewData. The value of TempData persists only from one request to the next. Retention is used to mark key to persist data so that it can retain for the next request.

We can also use TempData to pass data from one action to another action. Let's see an example.

Example

Controller

// TempDataController.cs

using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace ViewBagExample.Controllers
{
    public class ViewBagController : Controller
    {
        // GET: ViewBag
        public ActionResult Index()
        {
            List Courses = new List();
            Courses.Add("J2SE");
            Courses.Add("J2EE");
            Courses.Add("Spring");
            Courses.Add("Hibernates");
            TempData["Courses"] = Courses;
            return View();
        }
    }
}

View

// Index.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h2>List of Courses</h2>
    <ul>
        @{
            foreach (var Courses in TempData["Courses"] as List<string>)
            {
                <li> @Courses</li>
            }
        }
    </ul>
</body>
</html>

Output:

This index file produces the following output to the browser.

ASP View bag 3
Next TopicASP.Net Razor




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf