tags:

views:

113

answers:

4

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?

A: 

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

moi_meme
+1  A: 

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.

Stephane
A: 

Hi moi_meme and thanks for your help. I've tried doing that before but it doesn't suit my needs. I'll explain why. I've got an ascx page which is rendered 3 times or more inside the main aspx page. The reason why is because each ascx page belongs to a record from a certain table in our database. I've got something like this:

var IP = ViewData["childID"];

then at the end of the page I increment this var by doing the following:

ViewData["childID"] = (int)ViewData["childID"]+1;

I do this so that when the page is read over again, the integer on IP will be incremented. But when the page reads from the beginning, the value at the ViewData was not incremented, thefore the value in IP is still the same.

Hallaghan
this should be a comment or update your question
dotjoe
sorry, I'm new here, just figured out
Hallaghan
A: 

Right now, I'm rendering the pages like this:

<% Html.RenderPartial("Child-Pricing", (Tagus.Logistics.Web.Models.Contract.PricingModel)ViewData["HandlingInPricingModel"]); %>
<% Html.RenderPartial("Child-Pricing", (Tagus.Logistics.Web.Models.Contract.PricingModel)ViewData["StoragePricingModel"]); %>

<% Html.RenderPartial("Child-Pricing", (Tagus.Logistics.Web.Models.Contract.PricingModel)ViewData["HandlingOutPricingModel"]); %>

I seem to be unable to pass the ViewData variable that I have created at the controller, through the action that retrieves this page.

Hallaghan