Question

I have a controller with a method which returns a partial view and generates ViewData. Then, I have some methods, each of them returns Json objects and ViewData. But, the ViewData is not getting refreshed. How to refresh it? Is this possible?

public ActionResult FirstMethod() {
    ViewData["someList"] = ...;
    return PartialView(someOtherList);
}

public JsonResult SomeMethod()
{
    ViewData["someNewList"] = ...;
    return new JsonResult { ... };
}

But, although SomeMethod() is called after FirstMethod(), the ViewData which I use in my view is someList.

Was it helpful?

Solution

Is this possible?

No, it's not possible. The ViewData is a weakly typed dictionary which could be used (although I wouldn't recommend using it) to pass information between a controller and a view. Its lifetime is tied to that of the controller action execution pipeline. So once the view is rendered it's over. No controller, view, ViewData, ... exists anymore. Only HTML rendered in the client browser.

Then you send an AJAX request to the server again. This is completely new request that has nothing to do with the first one (which was used to render the view initially) and thus a new instance of the controller is created with its own ViewData. Setting ViewData in a controller action that returns JSON is useless because since this action will be invoked with javascript, all the information that you want to pass from the controller to the javascript success handler must be part of the JSON object that you return.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top