开发者

persisting links on an asp.net page - is this a job for viewstate?

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 link开发者_运维问答s 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?


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


This MSDN sample should help you.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜