Search code examples
asp.net-mvc-3viewdata

How to solve "The name 'ViewData' does not exist in the current context"


When I try and pass data to my view from a controller using ViewData I get the error in the title, when referencing the ViewData property in my view

I am using the Razor View engine, there are several posts around related to this, but they seem to be relevant to web forms implementations

I suspect there is an issue with how Razor is referenced: my config file has a number of warnings:

enter image description here

Those type references are warning : Invalid Module Qualification: Unable to resolve assembly System.Web.WebPages.Razor

The generic MVC stuff is working ok (using only Model references) but trying to access ViewData - no luck


Solution

  • In MVC3 ViewBag has been added. It's just the dynamic wrapper around the ViewData. Now you can use something like that :

    ViewBag.Title = "Test"; 
    

    One of the cool benefits of using ViewBag over ViewData is we don't have to cast ViewBag.Date to DateTime, ViewBag.Post to Post, and ViewBag.Tags to a string array before using them as such. This cuts down on the noise in the view.

    But as Darin said in the comment it's best to use a strongly typed views.

    Errors you're getting in web.config are not related to that. However I'm not sure what's the exact cause for these errors but it seems that it doesn't affect the application run.