开发者

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

开发者 https://www.devze.com 2023-01-02 01:35 出处:网络
I\'ve began开发者_如何学JAVA working with asp.net mvc very recently and I\'ve ran into a problem.

I've began开发者_如何学JAVA 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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消