How to declare a global variable in ASP.NET MVC page

I’ve began working with asp.net mvc very recently and I’ve ran into a problem.
I’ve got an aspx page which renders a few ascx pages. What I’d like to do is declare a global var at the aspx page so it is visible to all its childs. I tried <% var i = 0; %> but it wasn’t visible at the child pages.

What could I do?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

variables from a aspx page are not shared with the partial views.
The view is just a representation of a piece of data. You have to pass the data as a Model to each view you want to render, whether it’s a plain View or a PartialView.

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

If you want to pass a variable to a partial view, I would strongly recommend you to add this parameter to the model of the partial view, rather that to pass it additionally via the ViewDataDictionnary.

Method 2

You can add it to the ViewData and then pass the ViewData to the ascx with

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

see msdn on RenderPartial

So in your aspx page you’d do something like

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

And in your userControl you’d just retrive it and use it as you want

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

Another way would be to use RenderAction eand pass it as a parameter… so we’d need to know how you display your ascx.

see msdn on RenderAction


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x