开发者

Best way to toggle Div Visibility depending on Query String in c#?

I have about 20 div's in an aspx page. At any time, only one of them will be visible. I need to decide which div to show depending on the Query String.

http://...?mode=<ModeName>

The easy way would be to start with all div's invisible, then just put the QueryString in switch and write out cases for all the possible ModeNames (or get it in a big if-else structure)

I dont really like hard coding things because if in future if I add/remove any div then I need to "remember" to do the necessary changes in the places that toggle divs.

I was thinking of creating an enum with all names and passing that enum to the function so I can iterate through all enums and set visibility accordingly. This way I only need to add the div name in the top enum declaration. But it did not quite 开发者_JS百科work out that way (probably I'm too fiddly to get it to work)

Is Switch block my only way out of this? Does anyone have a better way to do this? Thanks in advance!


I would do some or all of the following:

  • Define the various modes of your window in an enumeration (public enum ModeNames {View, Edit, Create, Summary ...}). Make this enumeration generic but descriptive.
  • Expose a property DisplayMode that parses the QueryString into the enum value. You should have control of the ModeNames added to the QueryString, but since it is the query string and thus the client can type in whatever they like, I'd put in some error-checking that will show a "default" view mode if the QueryString is not one of the expected values.
  • Give the divs a runat=server and an ID attribute (I'm guessing you already have since you want to do this in C# and not JavaScript), and in your Page_PreRender handler, set the Visible property of each div (referenced by its ID as an object) to an expression evaluating whether the current DisplayMode is one of the modes in which this div should be visible (e.g. thisDiv.Visible = new[]{ModeNames.Create, ModeNames.Edit}.Contains(DisplayMode)).
  • Alternately, instead of the second step, you can do this in the markup, either by specifying the Visible property of the div (as a server-side object) using a similar inline expression evaluating DisplayMode, or by including an OnLoad JavaScript handler for the div (which no longer has to be server-side) that sets the visibility using the DOM, based on the same inline C# expression.


I suggest to set a relation between the data passed at querystring and the names(and ids) of the divs you want to handle.

The rest you should know, use an scriptmanager to execute Javascript code to hide/show proper divs depending of what you read from querystring,

Hope that helps,

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜