在 ASP.NET 页面上保留链接 - 这是 Viewstate 的工作吗?
我有一个母版页,上面有一个子导航链接部分:
<div id="sub_nav" runat="server"></div>
当我的主 asp:Menu 数据根据我所在页面的地址绑定时,我以编程方式使用超链接填充该母版页。
这工作正常,我所有正确的子菜单内容都显示在每个页面上。问题是,当其中一个页面进行回发时,我会丢失 sub_nav div 中的所有链接。
现在,我每次都可以用链接填充 div,无论母版页加载是否是回发,但我认为有更好的方法来做到这一点。我在想在 div 上启用视图状态及其内部的链接可能会通过回发保留它们,但显然这不是视图状态的工作原理。
这样做的正确方法是什么?
I've got a master page with a section for subnavigation links on it:
<div id="sub_nav" runat="server"></div>
I programatically populate this with Hyperlinks when my main asp:Menu data is bound depending on the address of the page I'm on.
This works fine and all my correct submenu stuff shows up on each page. The problem is that when one of these pages does a postback, I lose all the links that were in my sub_nav div.
Now, I could just populate the div with links every time regardless of whether the master page load is a postback or not, but I figured there is a better way of doing this. I was thinking enabling the viewstate on the div and links inside it might persist them through postbacks, but apparently that is not how viewstate works.
What is the correct way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Viewstate 仅存储控件的当前状态,而不存储控件本身。如果您要动态添加控件,请确保将它们添加到页面 init 方法中,无论回发如何
Viewstate only stores the current state of a control and not the controls by themselves. If you are dynamically adding controls make sure to add them on page init method irrespective of postback
此 MSDN 示例应该会对您有所帮助。
This MSDN sample should help you.
根据优秀文章真正了解 ViewState,这并不是 ViewState 的真正目的。此外,ViewState 会消耗额外的带宽,因此一般来说我们希望尽可能避免使用它。听起来这些数据应该“便宜”地获取(可缓存或诸如此类),因此我肯定会在每个请求上填充它并禁用这些控件上的 ViewState。
要理解 ViewState 的主要目的,请考虑一个具有两个按钮 btnA 和 btnB 以及两个标签 lblA 和 lblB 的页面。
当用户单击 btnA 时,页面回发并将 lblA 设置为“您单击了 A!”。
当用户单击 btnB 时,页面回发并将 lblB 设置为“您单击了 B!”。
使用 ViewState,页面会记住 lblA.Text 设置为“您单击了 A!”之前并恢复该值。如果没有 ViewState,如果用户单击 A,然后单击 B,页面只会显示“You clicked B!”因为没有任何东西可以存储 lblA 的先前值。
According to the excellent article TRULY Understanding ViewState, that's not really the purpose of ViewState. Furthermore, ViewState costs additional bandwidth so in general we want to avoid it if possible. It sounds like this data should be "cheap" to obtain (cacheable or whatnot), so I'd definitely populate it on every request and disable ViewState on those controls.
To understand the main purpose of ViewState consider a page with two buttons, btnA and btnB and two labels lblA and lblB.
When the user clicks btnA , the page posts back and sets lblA to "You clicked A!".
When the user clicks btnB, the page posts back and sets lblB to "You clicked B!".
With ViewState, the page remembers that lblA.Text was set to "You clicked A!" previously and restores that value. Without ViewState, if the user clicked A and then B, the page would only display "You clicked B!" because there's nothing to store the previous value of lblA.