Gautam Jain
Gautam Jain

Reputation: 6849

ViewData resets inside ASP.Net MVC controls

I have 2 instances of a user control (ascx) in a view page.

I set ViewData["xyz"] = "True" inside the user control.

The first instance would set ViewData["xyz"] to "True". However, this same value is not retained in the second instance of the user control.

I was expecting ViewData["xyz"] to be still "True", but it is null.

Please help.

What is the best way to have a shared variables across the user controls?

Upvotes: 0

Views: 535

Answers (2)

erikkallen
erikkallen

Reputation: 34401

Perhaps you can do ((ViewPage)Page).ViewData["whatever"] = "value";

A better idea is probably to not require shared state between the user controls,

Upvotes: 0

dariol
dariol

Reputation: 1979

Any logic should be done within controller. User controls (Views, Partial Views) shouldn't have logic that requires put data to ViewData collection. Views are only for presentation.

Upvotes: 3

Related Questions