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

13,671

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.

Share:
13,671
Hallaghan
Author by

Hallaghan

Developing in .Net for the web for the last 12 years. #SOreadytohelp

Updated on June 05, 2022

Comments

  • Hallaghan
    Hallaghan almost 2 years

    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?

  • yoozer8
    yoozer8 over 12 years
    Does this apply to two views inheriting from a shared view? If I were to declare and use a variable in the shared view, would I be able to override it in the inheriting views to change the output?
  • Stéphane
    Stéphane over 12 years
    I'm not sure to understand the case related to this question, but the view is just a class that renders html. But the variable will still not be shared across different calls to RenderPartial since that would create different instance of the partial view.