How to declare a global variable on an ASP.NET MVC page

I started working with asp.net mvc quite recently and am having a problem. I have an aspx page that displays multiple ascx pages. What I would like to do is declare a global variable var on an aspx page so that it is visible to all its children. I tried <% var i = 0; %> <% var i = 0; %> , but it was not visible on child pages.

What can I do?

+2
c # global-variables asp.net-mvc
Jun 04 '10 at 13:26
source share
2 answers

variables from an aspx page are not shared with partial views. A view is simply a representation of a piece of data. You must pass data in the form of a model for each view you want to visualize, whether it is a simple view or a PartialView.

 <% Html.RenderPartial("ViewName", Model, ViewDataDictionnary) %> 

If you want to pass a variable to a partial view, I highly recommend that you add this parameter to the partial view model, and to pass it additionally through ViewDataDictionnary.

+4
Jun 04 '10 at
source share

You can add it to ViewData and then pass ViewData to ascx using

 <% Html.RenderPartial("ViewName", Model, ViewData) %> 

see msdn on RenderPartial

So on the aspx page you will do something like

 <% ViewData["i"] = 0; %> 

And in your userControl you just retrieve it and use it however you want

 <% int i = (int)ViewData["i"] %> 

Another way would be to use a RenderAction eand pass it as a parameter ... so we will need to know how you are displaying your ascx.

see msdn on RenderAction

0
Jun 04 '10 at 13:40
source share



All Articles