mmcdole
mmcdole

Reputation: 92835

When is it acceptable to use the ViewData dictionary in ASP.NET MVC?

It seems like most people are leaning towards creating single ModelViews for each view (Thunderdome Principle) in lieu of stuffing in weakly typed items into the ViewData dictionary.

So, with this in mind, for what tasks should the ViewDictionary be used for then? Really small one-off views? Don't use it at all?

Upvotes: 1

Views: 1335

Answers (3)

Kevin Pang
Kevin Pang

Reputation: 41442

MasterPages strike me as a place where it's tough to get around them. Let's say you have a standard place on all your pages where error messages are going to be displayed. You could theoretically strong type the MasterPage and make sure that all view models inherit from some base class that gives you strong-typed access to the variable for setting the error message in your master page, but that seems like overkill. It's much more reasonable to do something like:

ViewData["ErrorMessage"] = "This is an error message";

and have your master page have a section displaying it:

<div class="error_message"><%= ViewData["ErrorMessage"] %></div>

Upvotes: 3

mxmissile
mxmissile

Reputation: 11682

Never, keep everything strongly typed. Helps with refactoring, that enough is reason alone.

Upvotes: 3

eu-ge-ne
eu-ge-ne

Reputation: 28153

I think the question is: use strongly-typed Views on not and when?. If your Views are not strongly-typed then you will be using ViewDataDictionary (mostly for simple/small apps). If you are using Unit Testing it is better to have View Model which can be simply tested.

Upvotes: 0

Related Questions