Close Sidebar

ASP.NET CSS Message Box Control

All web application need to display messages to users, including but not limited to erroneous or missing form entries and successful posting or saving of form data.  Typically, I would use a label control on the page and set the appropriate text (‘Successful Update’, ‘Missing Email Address’, etc..) and CSS Class.  Since I was using the same code on every page on every project.  I decided to create a server control(sbcMsgBox) in c# that would reduce the amount of code I would need to write and that would meet the following criteria:

  • Minimal code-behind.
  • Automatically show the control to prevent having to explicitly code visibility.
  • CSS based for easy styling.
  • Minimal, table-less markup.
  • Automatically set the appropriate styling (error, information, warning, success).
Figure 1. Sample message boxes produced by sbcMsgBox control 

In order to use the sbcMsgBox control in your project, you’ll need to download and copy the dll to your project’s bin folder.  If you want to see the control in your projects toolbox in order to drag and drop on a web page, simply right click on your toolbox and select ‘choose items’ from the pop up menu.  Once the screen loads, select browse and choose the dll from your projects bin folder.

You will also need to reference the control either on your page or in your web.config file.  To reference in your web.config, add the assembly to the <pages> section in <system.web>.

Figure 2. Referencing sbcMsgBox control in web.config 

<pages>
   <controls>
       <add assembly="sbcMsgBox" namespace="SBWebControls" tagPrefix="sbc" />
   </controls>
</pages>

To reference on your page, either drag the control onto your page in design mode or type the following at the top of the page.

Figure 3. Referencing sbcMsgBox in page

<%@ Register assembly="sbcMsgBox" namespace="SBWebControls" tagprefix="sbc" %>

The sbcMsgBox control defines the following Properties, which can be set at design time declaratively or at run time in the code behind:

  • ShowCloseButton – sets whether the message displayed can be closed.  If set to yes you should see a little close icon in the upper right hand corner.  The default value is true.
  • UseJQuery – sets whether jQuery is used to animate the closing of the message with a slide-up or fade-out animation.  This property is irrelevant if showCloseButton is set to false. The default value is false.
  • fxType – sets the JQuery animation for SlideUp or FadeOut. The default value is FadeOut..
  • BoxWidth – sets the width (ex., 350px) of the message box. If not set, the message will fill the width of the parent container control.
  • Centered – sets with the message box will be centered within the parent container.  This property only applies if the boxWidth is set.
  • Title – if set, the message displayed will show a title
  • ErrText, InfoText, WarnText & SuccessText – this is the message to display.  The control will render the appropriate style (warning, error, etc..).
  • ShowMessageImage – If set to ‘true’ the control will display a message icon (through css) appropriate to the type of message.  The default value is ‘true’.
  • CssClass – this sets the css class for styling the control.  The default class name is sbc_msgbox (see Figure 4).  If using the default style you don’t need to set this property.
    • <CssClass> – defines main message div
    • <CssClass> .closebutton – defines the image used for the close button.  You can use your own image or the one provided (close.png)
    • <CssClass> h4 – message title
    • <CssClass> p – message text
    • In order to style the different types of messages the control attaches the appropriate css class by appending (_err, _info, _warn, etc.) to the CssClass property (see Figure 5).
      • <CssClass>_err (see css below)
      • <CssClass>_info
      • <CssClass>_warn
      • <CssClass>_success
Figure 4. Default styling for sbcMsgBox control

/* Shared styling for all the different */
/* message types */
.sbc_msgbox
{
    padding:10px;
    color:#555;
    margin-bottom:10px;
    -moz-border-radius: 5px;
    border-radius: 5px;   }
.sbc_msgbox .closebutton
{
    width:7px;
    height:7px;
    background-image:url(close.png);
    background-repeat:no-repeat;
    cursor:pointer;
    float:right;
    margin-top:-1px;
    margin-right:-1px;
}
.sbc_msgbox h4
{
    margin:0;
    font-size:110%;
    padding:3px 0;
}

.sbc_msgbox p
{
    margin:0;
    padding:10px;
}
Figure 5. Style for each of the different message types (error, warning, etc…)

/* Style overrides for each of the different */
/* message types */
/* note: only displaying error message styling here. 

/* See css file in download for all message types */


/* error message */
.sbc_msgbox_err
{
    background-color:#fcfce1;
    border:solid 1px #ffcc00;
}
.sbc_msgbox_err h4
{
    border-bottom:solid 1px #ffcc00;
}
.sbc_msgbox_err p.msgimg
{
    background-image:url(error.png);
    background-repeat:no-repeat;
    background-position:left 10px;
    padding-left:25px;
}

The sbcMsgBox control defines the following Methods:

  • SetTitleText – this method takes three parameters (messageType, title and text) and simply sets the message type (info, error, etc..), title and text property in one line.

The demo project  contains several examples of setting properties in markup as well as some code behind examples.  I hope you enjoyed this article and find the sbcMsgBox control useful. Please comment or email me with any questions.  Happy Programming!

Simple Accordion Menu With JQuery & ASP.NET

In the following article I will show you how to create a simple accordion menu with JQuery and ASP.NET Visual Studio 2008.  There are many implementations of an accordion type menu on the web, including using JQuery UI and the ASP.NET AJAX Toolkit. For one reason or another these implementations did not work for me, so I decided to roll my own using JQuery and accomplish the following:

  1. Simple & valid markup
  2. Minimal JavaScript
  3. Auto slide open of the accordion menu based on the url
  4. Indication of which section is open and which link is active
  5. Degrade gracefully if JavaScript is turned off

If you look at the markup for the layout in the Master Page (‘MasterPage.master’), you’ll notice I’m using a three column CSS design and separated the menu and some content into user controls (located in the App_Controls folder).  None of this is pertinent to the accordion menu per se, but you may find that it is a good practice to separate out your design from the markup, as well as using user controls for content that will repeat on pages.

<div id="wrapper">
    <form id="form1" runat="server">
        <div id="page" >
            <!-- HEADER -->
            <uc1:head id="head2" runat="server" />
            <!-- LEFT CONTENT -->
            <div id='leftwrap'>
                <uc3:leftnav id="leftnav2" runat="server" />
            </div>
            <!-- MAIN CONTENT -->
            <div id="mainwrap">
            <div id="maincontent">
                <asp:ContentPlaceHolder id="main" runat="server">
                </asp:ContentPlaceHolder>
            </div>
            </div>
            <!-- RIGHT CONTENT -->
            <div id="rightwrap">
                <uc2:rightnav ID="rightnav2" runat="server" />
            </div>
            <!-- FOOTER -->
            <div id="footer">
                <uc4:footer id="footer2" runat="server" />
            </div>
        </div>
    </form>
</div>

The accordion menu markup is located in a user control called ‘leftnav.ascx’ (see below for the accordion menu markup).  Each menu heading item is comprised of an <h3> tag with a nested <a> tag. The link section is comprised of a simple <ul> wrapped with a <div>.  As you can see, the menu markup is relatively simple and straightforward.

<div id="accordion">

        <h3>
        <a href="javascript:void(0);" runat="server" id="aServices">Services</a></h3>

        <div class="acsection" runat="server" id="divServices">
        <ul>
            <li runat="server" id="liService1"><a href="service1.aspx">Service 1</a></li>
            <li runat="server" id="liService2"><a href="service2.aspx">Service 2</a></li>
        </ul>
        </div>

        <h3>
        <a href="javascript:void(0);" runat="server" id="aArticles">Articles</a></h3>

        <div class="acsection" runat="server" id="divArticles">
        <ul>
            <li runat="server" id="liArticle1"><a href="article1.aspx">Article 1</a></li>
            <li runat="server" id="liArticle2"><a href="article2.aspx">Article 2</a></li>
        </ul>
        </div>

        <h3>
        <a href="javascript:void(0);" runat="server" id="aProducts">Products</a></h3>

        <div class="acsection" runat="server" id="divProducts">
        <ul>
            <li runat="server" id="liProduct1"><a href="product1.aspx">Product 1</a></li>
            <li runat="server" id="liProduct2"><a href="product2.aspx">Product 2</a></li>
        </ul>
        </div>

    </div>

The JavaScript for the accordion menu only requires a few lines of code.  When the document is ready ($document.ready), I attach a click event using JQuery to each <h3> tag within an element with an id of ‘accordion’, which in this case is the wrapping <div> tag. To accomplish the opening and closing of the menu, only one line of code is needed.  When the <h3> item is clicked, the next <div> section is opened and all the sibling <div> sections are closed.  That is it!

$(document).ready(function() {

    // set up the accordion
    $("#accordion>h3").click(function() {
        $(this).next("div").slideToggle(500).siblings("div").slideUp(500);
    });

    // show active menu section
    setTimeout('$("#accordion>div.activesec").slideToggle(800)', 100);

});

To accomplish the auto opening and styling of the appropriate section and links based on the url, we’ll use a little C# code, JavaScript and CSS.  If you look at the code for ‘leftnav.ascx.cs’ below, I’m simply getting the page name and adding style classes to the appropriate tags.  I’m adding ‘active’ class to the <a> tag and ‘subactive’ class to the <li> tag to indicate that they are selected with a little arrow. In addition, I’m adding ‘activesec’ class to the <div> that wraps the links to highlight the top and bottom borders of the section (see below for the accordion CSS).  The ‘activesec’ class serves a dual purpose, as I will also use this class to select the active section to open.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // get page
            string pageName = Request.Url.ToString().ToLower();
            int pos = pageName.LastIndexOf("/");
            pageName = pageName.Substring(pos + 1);

            switch (pageName)
            {
                case "article1.aspx":
                    this.aArticles.Attributes["class"] = "active";
                    this.liArticle1.Attributes["class"] = "subactive";
                    this.divArticles.Attributes["class"] = "acsection activesec";
                    break;
                case "article2.aspx":
                    this.aArticles.Attributes["class"] = "active";
                    this.liArticle2.Attributes["class"] = "subactive";
                    this.divArticles.Attributes["class"] = "acsection activesec";
                    break;
                case "service1.aspx":
                    this.aServices.Attributes["class"] = "active";
                    this.liService1.Attributes["class"] = "subactive";
                    this.divServices.Attributes["class"] = "acsection activesec";
                    break;
                case "service2.aspx":
                    this.aServices.Attributes["class"] = "active";
                    this.liService2.Attributes["class"] = "subactive";
                    this.divServices.Attributes["class"] = "acsection activesec";
                    break;
                case "product1.aspx":
                    this.aProducts.Attributes["class"] = "active";
                    this.liProduct1.Attributes["class"] = "subactive";
                    this.divProducts.Attributes["class"] = "acsection activesec";
                    break;
                case "product2.aspx":
                    this.aProducts.Attributes["class"] = "active";
                    this.liProduct2.Attributes["class"] = "subactive";
                    this.divProducts.Attributes["class"] = "acsection activesec";
                    break;
            }
        }
    }

If you look at the Javascript code above, you’ll notice that I’m using the setTimeout method to execute some code 100 milliseconds after the page has loaded.  Using JQuery selector, I’m sliding open a <div> with the class ‘acsection’ (which was set in the C# code), within an element with an id of ‘accordion’.

#accordion{
    list-style-type:none;
    margin:0;
    padding:0;
    width:170px;
}
#accordion ul{
    margin:0;
    padding:10px 0;
    margin-left:10px;
}
#accordion li{
    list-style-type:none;

}
#accordion li a{
    color:#666;
    text-decoration:none;
    padding:3px 0;
    display:block;
    padding-left:12px;
}

#accordion li a:hover{
    text-decoration:underline;
    background-repeat:no-repeat;
    background-position:left center;
}

#accordion li.subactive
{
    background-image:url(../images/lnbullert.gif);
    background-repeat:no-repeat;
    background-position:left center;
}

#accordion li a:focus{
    outline:none;
}
#accordion .acsection{
    border:dotted 1px #B3B3B3;
    margin:0;
    border-left:none;
    border-right:none;
    width:170px;
}

#accordion h3{
    margin:0;
    padding:5px 0;

}
#accordion h3:focus {
    outline: none;
}
#accordion h3 a{
    color:#777;
    text-decoration:none;
    display:block;
    padding-left:12px;
    background-image:none;
}
#accordion h3 a.active
{
    color:#555;
    background-image:url(../images/lnMbullert.gif);
    background-repeat:no-repeat;
    background-position:left center;
}
#accordion h3 a:focus{
    outline:none;

}

#accordion h3 a:hover{
    text-decoration:underline;
    color:#555;
    background-repeat:no-repeat;
    background-position:left center;
}

In the case when JavaScript is turned off in a user’s browser, I simply allow all the menu links to be visible. I include a few lines of JavaScript at the bottom of the Master Page (see code below) to hide all the <div> sections with an id of ‘acsection’.  That’s it!

   // set up accordion by hiding link sections
   // if no javascript then all links will be displayed as the below code
   // will not execute
   var styleObject = getCSSRule('#accordion .acsection');
   styleObject.style.display = 'none';

I hope you enjoyed this article and have found it useful.  Please comment or email me with any questions.  Happy Programming!

Recommended Reading