ViewDataandViewBagin ASP.NET Core areweakdatatypes(ie loose types), ie we do not need to explicitly define the data type.Some cases useViewBagandViewData:

Data transfer between … For example
Controller andView Transfers data to a drop box (Select box).
View andLayout View Resets the content of the<title>element in the Layout View from a child view.
Partial Viewand View A widget that displays data depend on the page the user visits.

Since they are weak types, theViewBagandViewDataare processed at runtime and will not check the data type at compile-time as the view model should be more error-prone.Therefore, we should only use them when we need to transmit a small amount of data and easy to control.

Note that the ViewBag is not available inRazor Pages.

ViewData

Is aView Data Dictionaryobject that is accessed through a string key(white space is allowed).Withstringdata type, we can store and use directly, and with an object type, when we use it we will have to cast to specific data type.For example, when passing an object from Controller to View:

// Controller
public IActionResult SomeAction()
{
    // Lưu dữ liệu kiểu string
    ViewData["Greeting"] = "Hello";

    // Lưu dữ liệu kiểu object
    ViewData["Address"] = new Address()
    {
        Name = "Huy",
        City = "Hanoi",
    };

    return View();
}

 

Using ViewData on the View:

@{
    // Address khng phải l 1 string nn sẽ cần p kiểu
    var address = ViewData["Address"] as Address;
}

@ViewData["Greeting"] World!

<address>
    @address.Name<br>
    @address.City
</address>

 

ViewBag

As aDynamic ViewDataobject, it is a View Data wrap that allows flexible access to the object.The ViewBag also allows us to use dynamic properties(using dots instead of square brackets like ViewData). Using the ViewBag is similar to ViewData, but it is more convenient because it does not need to be pressed.For example:

// Controller
public IActionResult SomeAction()
{
    // Lưu dữ liệu kiểu string
    ViewBag.Greeting = "Hello";

    // Lưu dữ liệu kiểu object
    ViewBag.Address = new Address()
    {
        Name = "Huy",
        City = "Hanoi",
    };

    return View();
}

 

Use the ViewBag on the View:

@ViewBag.Greeting World!

<address>
    @ViewBag.Address.Name<br>
    @ViewBag.Address.City
</address>

 

Read More:

Source:Weakly-typed data (ViewData and ViewBag)

Leave a Comment

Close