[英]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. 我最近开始使用asp.net mvc,但遇到了问题。 I've got an aspx page which renders a few ascx pages.
我有一个aspx页面,它呈现了一些ascx页面。 What I'd like to do is declare a global var at the aspx page so it is visible to all its childs.
我想做的是在aspx页面上声明一个全局变量,以便对其所有子代可见。 I tried
<% var i = 0; %>
我试过
<% var i = 0; %>
<% var i = 0; %>
but it wasn't visible at the child pages. <% var i = 0; %>
但在子页面上看不到。
What could I do? 我能做什么?
variables from a aspx page are not shared with the partial views. Aspx页面中的变量不会与部分视图共享。 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.
您必须将数据作为模型传递给要渲染的每个视图,无论是纯视图还是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. 如果要将变量传递给局部视图,强烈建议您将此参数添加到局部视图的模型中,而不是通过ViewDataDictionnary附加传递它。
You can add it to the ViewData and then pass the ViewData to the ascx with 您可以将其添加到ViewData,然后通过以下方式将ViewData传递给ascx:
<% Html.RenderPartial("ViewName", Model, ViewData) %>
see msdn on RenderPartial 在RenderPartial上查看msdn
So in your aspx page you'd do something like 因此,在您的aspx页面中,您将执行以下操作
<% ViewData["i"] = 0; %>
And in your userControl you'd just retrive it and use it as you want 在userControl中,您只需检索它并根据需要使用它
<% 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. 另一种方法是使用RenderAction eand并将其作为参数传递...因此我们需要知道如何显示ascx。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.