leora
leora

Reputation: 196741

is there any legitimate reason to use ViewData in asp.net mvc

with model binding where you can build up an object to ship and bind to the view, is there any reason to ever use ViewData ?

Upvotes: 0

Views: 155

Answers (3)

Nathan Taylor
Nathan Taylor

Reputation: 24606

ViewData seems to exist as a simple, convenient approach to something that you really should do a syntactically cleaner way. The MVC equivalent of an ArrayList I suppose- works just fine but you'd be hard pressed to come up with a truly legitimate excuse for using it in good code.

One exception I can think of for using it would be including something dynamic in ALL of your pages that gets appended in an ActionFilter or base Controller class- for example "WebsiteTitle". Rather than attempting to tamper with the data being returned by a Controller action it might make more sense to include something like that in the ViewData collection- perhaps prefixed with some unique identifier to make it obvious it was being included outside the controller action. ViewData["Base_WebSiteName"], for example.

Upvotes: 2

Kelsey
Kelsey

Reputation: 47766

I am pretty new to MVC but what little I have done, I have written custom objects for all my views.

The only reason I could think of is to save time. You need to whip something up fast and maybe there are multiple objects of data on a page and something extra and you don't want to take the time to write an object putting it all together. Is this a good reason? In my opinion no.

Upvotes: 0

griegs
griegs

Reputation: 22770

I can't forsee an instance where I would use it unless I had static information coming in from a database for a page/master that then got displayed in say a <p> or some such.

If the page was a read only page that say returned a list of items and I also wanted to display text from a DB then I might use ViewData.

But that's kind of an exception. If I was returning a list of items from a DB along with some other stuff then I would create a Form View Model and simply include any other data in with it.

So rarely I guess is my answer here.

Upvotes: 2

Related Questions