Can you use dot notation with ViewData in Razor Pages?

Viewed 95

I'm using Razor Pages and trying to access a property from ViewData:

@{
    ViewData["Property"] = "Value";
}

I know this works:

<h1>@ViewData["Property"]

However, the app crashes when I try to access it with dot notation:

<h1>@ViewData.Property</h1>

Why does this hapen?

I know dot notation works with ViewBag since it allows me to access properties dynamically.

2 Answers

ViewData is object of type ViewDataDictionary which is actually IDictionary<string,object> while ViewBag is dynamic. dynamic allows to use dot notation while dictionary in C# allows to get values only via [key], so your app crashes because there is no such property Property in ViewDataDictionary even if there is such key.

The ViewData is IDictionary which means you can access data using key (ViewData[yourkey]). But your concern is also valid, we want to access property so we can reduce risk of some teammates mis type the key.

And for that reason, I always prefer to use @Model.YourProperty. Then next question, if you got a common used field for all pages such as Languague, LoginName, ... Then I suggest to have a base Model to contain all those properties. And all page model needs to inherit/implement those properties.

Related