2

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.