Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / Javascript
Tip/Trick

How to Dynamically Show or Hide sections of a Sharepoint Web Page

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
17 Jun 2015CPOL3 min read 14.1K   1  
Use C# and jQuery to control the visibility of a section of a Web Part or Web Page

Win Enemies and Alienate People

Or is it supposed to be, "Win Affluent Friends" or...well, never mind - onward!

If you want an incredible morphing, now-you-see-it, now-you-don't section of a Web Part on a Sharepoint page, you can dynamically create the controls using server-side (C#) code in the *.ascx.cs file, and then add client-side (jQuery) code to the corresponding *.ascx file to react to some user action to either hide or unhide (or slideup and slidedown, as I'm going to show here).

First, you can dynamically create controls for your Web Part with code like this:

C#
private void GenerateSection2()
{
    HtmlTable tblSection2 = null;
    var section2Hdr = new Label
    {
        CssClass = "dplatypus-webform-field-label",
        Text = "<h2>Section 2: Requester Information</h2>"
    };
    this.Controls.Add(section2Hdr);

    tblSection2 = GetSection2Table(); // This creates an HtmlTable, adds many controls to it, and passes it back
    this.Controls.Add(tblSection2);
}

This works, for creating controls that will always display (providing GenerateSection2() is called from somewhere else in your code, such as from the PageLoad() event (in my case, it is called conditionally from there, depending on the state of a Web Part Editor)).

But what if you want to conditionally hide this section of controls? To do so, you can put them all within a "DIV" which, in the ASP.NET / Sharepoint world, is a "Panel". So you can refactor the method like so:

C#
private void GenerateSection2()
{
    Panel panelSec2 = new Panel(); // DIV
    panelSec2.ID = "panelSection2";

    HtmlTable tblSection2 = null;
    var section2Hdr = new Label
    {
        CssClass = "dplatypus-webform-field-label",
        Text = "<h2>Section 2: Requester Information</h2>"
    };
    panelSec2.Controls.Add(section2Hdr);

    tblSection2 = GetSection2Table();
    panelSec2.Controls.Add(tblSection2);
    this.Controls.Add(panelSec2);
}

Now the Label and the Table are added to the Panel (DIV), and then THAT is added to "this" (the Web Part). And since the Div/Panel has been provided with an ID, you can access it via jQuery and act on it, which, in effect, affects the whole panel, that is to say, all the controls on the panel. Or, in this case, we hide (slideup) the panel, so everything is hidden/out of the way. You could also use the jQuery "hide()" method instead of "slideUp()" but it's not as spiffy. You can win friends and influence people by using slideUp(). Don't forget to send me my 15% cut of the extra millions you will earn as a result.

Anyway, on to the jQuery, which should be added to the end of the *.ascx file. Assume that the control that determines the visibility of the section is a checkbox with the ID "ckbxPaymentForSelf"; this code would fire when that checkbox was checked or unchecked and, based on that state, either slide up (hide, in the forementioned spiffy and impressive manner) or slide down (re-display, with a similar rakish fluorish). Of course, you can replace the conditional with anything else of your choosing.

jQuery
$(document).on("change", '[id$=ckbxPaymentForSelf]', function () {
    if (this.checked) {
        $('[id$=panelSection2]').slideUp();
    }
    else {
        $('[id$=panelSection2]').slideDown();
    }
});

When Succotashes Suffer, Everyone Suffers

Note: The reason why the "ends with" id-locating syntax is used ("id$=") is because Sharepoint generates some long-donkeyed bunch of "junk" and prepends it to the ID provided; in my case, the ID actually generated for the panel is "ctl00_ctl24_g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33_ctl00_panelSection2" - sufferin' succotash! And so the "ends with" must be used to identify the panel.

At any rate, this is all that is needed to create sections of a Web Part that are hidden or re-displayed at will. Your will, that is - not Trespasser's Will.

What If You Want to Show/Hide Parts (subsections) of a Section?

This works great (if I do say so myself) for showing/hiding an entire section, but what if you have a section that contains parts that you may want to condtionally show/hide?

This is what I did for that scenario: I marked the related elements with an ID that ended with a common string, in this case they end with "_MailStopRow":

C#
var mailStopStr = new Label
{
    CssClass = "finaff-webform-field-label",
    Text = "Mail Stop:",
    ID = "mailstoplabel_MailStopRow"
};
boxMailStop = new TextBox
{
    CssClass = "finaff-webform-field-input",
    ID = "mailstoptextbox_MailStopRow"
};

var DeptDivStr = new Label
{
    CssClass = "finaff-webform-field-label",
    Text = "Dept / Div Name:",
    ID = "deptdivlabel_MailStopRow"
};
boxDeptDivSection1 = new TextBox
{
    CssClass = "finaff-webform-field-input",
    ID = "deptdivtextbox_MailStopRow"
};

In this way, I can act on all elements that end with "_MailStopRow" - conditionally hiding (sliding up) or showing (sliding down) them. Here is the jQuery for that:

jQuery
$(document).on("change", '[id$=ckbxPaymentForSelf]', function () {
    if (this.checked) {
	. . . // code elided to focus on the part under discussion
        $('[id$=_MailStopRow]').slideDown();
    }
    else {
	. . . // code elided to focus on the part under discussion
        $('[id$=_MailStopRow]').slideUp();
    }
});

Fancy Pants Double Agent

When you do this, you can consider yourself a fancy-pants double agent, one who is working both in the nitty-gritty big-iron world of server-side code (C#) - not for the faint of heart! AND in the way-cool labyrinths of client-side code (jQuery) - not for the soft of spirit! Pat yourself on the fanny, let out a war whoop or two, and perform a triple somerset as an unbidden encore!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
-- There are no messages in this forum --