• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Sunday, August 30, 2020

ViewBag in ASP.NET Core MVC

 Admin     August 30, 2020     .Net, .Net Core, .Net Core MVC, Asp.Net, C#     No comments   

In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article before proceeding to this article where we discussed ViewData in ASP.NET Core MVC application. As we already discussed in the ASP.NET Core MVC application, we can pass the data from a controller to a view using ViewData, ViewBag, and strongly typed view model. As part of this article, we are going to discuss the following pointers.
  1. What is ViewBag in ASP.NET Core MVC?
  2. How to Pass and Retrieve data From ViewBag in ASP.NET Core MVC?
  3. Example to understand ViewBag in ASP.NET Core MVC
  4. Difference between ViewData and ViewBag in ASP.NET Core MVC
What is ViewBag in ASP.NET Core MVC?
The ViewBag in ASP.NET Core MVC is one of the mechanisms to pass the data from a controller action method to a view. If you go to the Controller base class, then you will find the following signature of the ViewBag property.
ViewBag in ASP.NET Core MVC

So the ViewBag is a dynamic property of the Controller base class. The dynamic type is introduced in C# 4.0. It is very much similar to the var keyword that means we can store any type of value in it but the type will be decided at run time rather than compile-time.

The ViewBag transfers the data from the controller action method to a view only, the reverse is not possible.

How to Pass and Retrieve data From ViewBag in ASP.NET Core MVC?
The point that you need to keep in mind is, ViewBag is operating on the dynamic data type. So we don’t require typecasting while accessing the data from a ViewBag. It does not matter whether the data that we are accessing is of type string or any complex type.

ViewBag in ASP.NET Core MVC with String Type:
ViewBag in ASP.NET Core MVC with String Type

ViewBag in ASP.NET Core MVC with Complex Type:
ViewBag in ASP.NET Core MVC with Complex Type

Example of ViewBag in ASP.NET Core MVC:
Let us see an example to understand how to use ViewBag to pass data from a controller to a view. We are going to work with the same example that we worked in our previous article with ViewData. So, modify the Details action method of HomeController class as shown below.
using FirstCoreMVCApplication.Models;
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Details()
        {
            ViewBag.Title = "Student Details Page";
            ViewBag.Header = "Student Details";
            Student student = new Student()
            {
                StudentId = 101,
                Name = "James",
                Branch = "CSE",
                Section = "A",
                Gender = "Male"
            };
            
            ViewBag.Student = student;
            
            return View();
        }
    }
}
As you can see in the above example, here we are using the dynamic properties Title, Header, and Student on the ViewBag.

Accessing the ViewBag in a View in ASP.NET Core MVC
Now we will see how to access the ViewBag data within an ASP.NET Core MVC view. So, modify the Details.cshtml view file as shown below.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
    <h1>@ViewBag.Header</h1>
    @{
        var student = ViewBag.Student;
    }
    <div>
        StudentId : @student.StudentId
    </div>
    <div>
        Name : @student.Name
    </div>
    <div>
        Branch : @student.Branch
    </div>
    <div>
        Section : @student.Section
    </div>
    <div>
        Gender : @student.Gender
    </div>
</body>
</html>
As you can see, here we are accessing the data from the ViewBag using the same dynamic properties Title, Header, and Student. Now run the application and navigate to the “/Home/Details” URL and you will see the data as expected on the webpage as shown in the below image.
Output of ViewData

The ViewBag is a dynamic property that is resolved at runtime; as a result, here also it will not provide compile-time error checking as well as intelligence support. For example, if we miss-spell the property names of the ViewBag, then we wouldn’t get any compile-time error rather we came to know about the error at runtime.

Difference between ViewData and ViewBag in ASP.NET Core MVC
  1. In ASP.NET Core MVC, we can use both ViewData and ViewBag to pass the data from a Controller action method to a View.
  2. The ViewData is a weakly typed dictionary object whereas the ViewBag is a dynamic property. Both ViewData and ViewBag are used to create a loosely typed view in MVC.
  3. In ViewData, we use string keys to store and retrieve the data from the ViewData dictionary whereas in ViewBag we use the dynamic properties to store and retrieve data.
  4. Both the ViewData keys and ViewBag dynamic properties are resolved only at runtime. As a result, both do not provide compile-time error checking and because of this, we will not get intelligence support.
  5. So if we misspell the key names or dynamic property names then we will not get any compile-time error rather we came to know about the error only at run time. This is the reason why we rarely used ViewBag and ViewData in our application.
The best and preferred approach in MVC to pass data from a controller action method to a view is by using a strongly typed model object. When we use a strongly typed model object then only our view becomes a strongly typed view.

In the next article, I am going to discuss the Strongly Typed Views in ASP.NET Core MVC application with an example. Here, in this article, I try to explain ViewBag in ASP.NET Core MVC application. I hope this article will help you with your needs.

Summary:
I hope this post will be helpful to understand the concept of ViewBag in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape