DotNetSlackers: ASP.NET News for lazy Developers

Monday, February 15, 2016

AjaxControlToolkit’ TabContainer control’ Javascript functions in ASP.NET

In this blog we will start with a common requirement for the tab container control i.e. setting focus to a tab using javascript and later at the end of this blog we will also see some important javascript functions available with ASP.NET AJAX Tab Container control.
One of the coolest controls in the ASP.NET AJAX is the TabContainer. Recently I had the requirement to show controls in tabs and also if there was any validation error in any of the tab I need to set focus on that tab as well. So if you also have the same requirement like you wanted to set focus to a particular tab of ASP.NET Ajax TabContainer control using javascript then read on. Below is the html code for the page having a tab container and some other asp.net controls like the validation control, validator callout etc.



<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AJAXControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <AJAXControls:TabContainer runat="server" ID="tabContainer">
            <AJAXControls:TabPanel ID="firstTab" HeaderText="First Tab" runat="server">
                <ContentTemplate>
                    <asp:Label ID="Label1" runat="server">You are in the First tab. <br /> Press the submit button to see the validation result.</asp:Label>
                </ContentTemplate>
            </AJAXControls:TabPanel>
            <AJAXControls:TabPanel ID="secondTab" HeaderText="Second Tab" runat="server">
                <ContentTemplate>
                    <label id="Label2" runat="server">Please select a value from the drop down: </label>
                    <!--ASP.NET Drop down control-->
                    <asp:DropDownList ID="status" runat="server" >
                        <asp:ListItem Selected="True" Text="Select" Value="0" />
                        <asp:ListItem Text="One" />
                        <asp:ListItem Text="Two" />
                        <asp:ListItem Text="Three" />
                    </asp:DropDownList>
                    <!--ASP.NET Required Field Validator to validate the drop down.-->
                    <asp:RequiredFieldValidator ID="statusValidator" runat="server" ErrorMessage="Please choose a value other than 'Select'" ControlToValidate="status" InitialValue="0" Visible="true" Display="None">
                    </asp:RequiredFieldValidator>
                    <AJAXControls:ValidatorCalloutExtender ID="statusValidator_ValidatorCalloutExtender"
                        runat="server" TargetControlID="statusValidator">                     </AJAXControls:ValidatorCalloutExtender>                   
                </ContentTemplate>
            </AJAXControls:TabPanel>
        </AJAXControls:TabContainer>
        <br />
        <asp:Button ID="submit" Text="Submit" OnClientClick="javascript:return ValidatePage();"
            runat="server" />
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    </div>
    </form>
</body>
</html>

So in the above html code you can see we have an AjaxControlToolkit TabContainer control with two TabPanels having id as “firstTab” and “secondTab”. The first tab has a label control and the second tab has a dropdown control with a validation control attached to it and a ValidatorCalloutExtender control attached to the validation control. Also we have a submit button with “OnClientClick” event calling a javscript function called “ValidatePage”. Now the problem is whenever the submit button is pressed and if there is a validation error in the second tab the user is not informed of the same, reason being he is in the first tab and error has happened in the second tab. When the user manually clicks on the second tab he is able to see the error and if he doesn’t click the second tab the user is oblivious of the error. The solution to the problem is to set focus on the second tab whenever there is a validation error in the second tab. The javascript solution for the same is pasted below.


<script language="javascript" type="text/javascript">
function ValidatePage()
{
    // Getting the validation control using the new $get function.
    var valCntl = $get('<%=statusValidator.ClientID%>');
    if (valCntl != undefined && valCntl != null)
    {
        /*ValidatorValidate function executes the validation logic associated with the validation control. */
        ValidatorValidate(valCntl); 
    /*isvalid property is set to a boolean value by the ValidatorValidate based on whether the validation logic associated with the validation control was successful or not. */
        if (!valCntl.isvalid)
        {
        /*User defined method to hide the validator callout control.
            hideValidatorCallout(); */
        /*Retrieving the tab container control using new $get javascript function. */
            var tabContainer = $get('<%=tabContainer.ClientID%>');
            if (tabContainer != undefined && tabContainer != null)
            {
                tabContainer = tabContainer.control;
                tabContainer.set_activeTabIndex(1);
                showValidatorCallout();
            }
            return false;
        }
        return true;
    }
}
function hideValidatorCallout()
{    
    /*Below code hides the active AjaxControlToolkit ValidatorCalloutExtender control. */
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.hide();
}
function showValidatorCallout()
{
    /*Gets the AjaxControlToolkit ValidatorCalloutExtender control using the $find method. */
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout = $find('<% =statusValidator_ValidatorCalloutExtender.ClientID %>');
    //Below code unhides the AjaxControlToolkit ValidatorCalloutExtender control.
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.show(true);
}
</script>
If you see in the above code we are calling ValidatePage javascript method on the button’ OnClientClick event. Inside the function we are making a call to the ValidatorValidate method with the validation control as the argument. Once that is done I am checking whether the validation logic associated with validation control has executed successfully or not by checking the isvalid property of the validation control. If the validation is not successful I am getting the tab container control using the “$get” javascript method. Once the tab container is retrieved the following two lines sets the focus to the desired tab.

tabContainer = tabContainer.control; 
tabContainer.set_activeTabIndex(1); 
Once you retrieve the tab container object using the “control” property one can use “set_activeTabIndex” to set the focus to the required tab. The “set_activeTabIndex” method takes an integer (tab index) value as the argument. Using the “set_activeTabIndex” javascript method one can set focus to the required tab.
I have used a new javascript function called “$get” to retrieve an element. In my previous blog I have used “$find”, we will see the difference between these two in my next blog but for the time being just understand that “$get” is the short cut for “document.getElementById” javascript method.
Some other useful tab container control’ javascript functions
Below I have listed some of the important javscript functions which may be of use for developers like us. These methods can be used only after one has retrieved the ASP.NET AJAX TabContainer control using the following code “TABCONTAINER_CONTROL.control” as shown in the above codes.



MethodExplanation
get_activeTab()
returns the current active tab javascript object i.e. the tab which is in focus. This javascript function gets the active tab object.
get_activeTabIndex()
gets the active tab index. The function returns an integer value of the active tab.
get_id()gets the id of the tab container control.
get_tabs()gets an array of all the tabs in a tab container control. The function returns a javascript array containing all the tabs in the tab container control.
get_visible()
returns a boolean value indicating whether the tab container is visible or not.
getFirstTab()gets the first tab in the tab container control. The function returns a tab having tab index 0.
getLastTab()gets the last tab in the tab container control. The function returns a tab object having tab index = (tab count) –1.
getNearestTab()
gets the nearest tab. If the current tab index is 0 then the method will return second tab i.e. the tab having tab index as 1 and if the tab index is greater than 0 the function will return the previous tab i.e. the tab having index = [Current Tab Index] – 1.
getNextTab()
gets the next tab in the tab container control i.e. if the current active tab is the last tab then the function will return the first tab as the next tab else it will return the next tab ([Current Tab Index] + 1)
getPreviousTab()
gets the previous tab in the tab container control i.e. if the current tab index is 0 then the function returns the last tab else it returns the previous tab ([Current Tab Index] - 1)
set_activeTab(tabControl)
sets the active tab. The function takes a tab object as its argument and sets the tab as the active tab.
set_activeTabIndex(integer)
functions takes an integer value starting from 0 to tab collection length – 1 as an argument and sets the tab’ index matching the integer value as the active tab.
set_id()
sets the id for the current tab container control.
set_visible(Boolean)
function takes a Boolean value and based on the value, hides or shows the tab container. The function/property makes the whole tab container control visible or invisible. To make individual tabs visible or invisible you need to work with the tabs property as shown in the below table.
Individual Tab object’ javascript functions
The above functions are related to the tab container control. There may situation where one might want to work with individual tab objects. To work with individual tabs one has to retrieve the individual tab by making us of any of the above tab retrieval functions from the table and then one can work with the individual tab. Sample e.g to retrieve individual tab is given below.

tabContainer = tabContainer.control;
//Retrieving the tab using the get_activeTab method/property
var tab = tabContainer.get_activeTab();
var headerText = tab.get_headerText();
alert(headerText);
//Another way of retrieving the tab using the get_previousTab method/property
tab = tabContainer.getPreviousTab();
alert(tab.get_tabIndex());
Once you have retrieved the individual tab using any of the above methods you can make use of some of the useful methods listed in the table below to work with the tab object. The methods listed in the below table are not the complete list but they are some of the methods which I feel may be useful for developers.


MethodsExplanation
addCssClass(className)sets the CSS class. The function takes the CSS class name as the argument. You can make use of this javascript function to change the CSS class of a tab at runtime through javascript.
get_enabled()
gets a Boolean value indicating whether the tab is enabled or not (disabled). The function returns true or false.
get_headerText()
gets the header text of the tab. The function returns string containing the header text.
get_id()gets the id of the tab.
get_tabIndex()gets the tab index of the tab object. The function returns an integer.
get_visible()gets whether the tab is visible or not. The function returns a boolean value.
removeCssClass(className)
removes the CSS class based on the class name passed in the argument.
set_enabled(Boolean)
enables or disables the tab object based on the boolean value passed.
set_headerText(string)
function sets the header text for tab. Functions takes a string as an argument and sets the string as the header text.
set_id()sets the id for the tab.
set_visible(Boolean)
sets the visibility of the tab based on the boolean argument passed. The boolean value makes the tab visible or invisible.

BootStrap Datetime Picker Example

In this article I will show how to use bootstrap datetime picker control with a simple example.

Introduction

Bootstrap provides so many UI related things like css, styling, animation, useful tools like datetime picker, tables etc. which can be directly used to create interactive UI. In this article I will try to show how can you add bootstrap datetime picker control to your page in simple steps. Let's start step by step.
bootstrap datetime picker

HTML

create a html file and name it index.html and add a textbox in your page. Copy below code.
    <h3>BootStrap Datetime Picker Example</h3>
    <hr />
    <div>Click textbox to open datetime picker: <input type="text" id="fromDate" class="datepicker" /></div>

Add reference

Add bootstrap css and script reference to your page. This sample requires bootstrap-datepicker.css and bootstrap-datepicker.js files to work. You can download these files from bootstrap site or you can also download sample code fromDownLoad Code link above.
    <script type="text/javascript" src="JS/jquery-1.10.2.min.js"></script>
    <link href="DatePicker/bootstrap-datepicker.css" rel="stylesheet" />
    <script src="DatePicker/bootstrap-datepicker.js"></script>

Script

Add these lines of code in script block.
<script>
    $(document).ready(function () {
        $(".datepicker").datepicker({ format: 'dd/mm/yyyy', autoclose: true, todayBtn: 'linked' })
    });
</script>
Run the index.html and you will find your datetime picker ready. It was very simple to implement. Hope this can help you.

Understanding Structured, Unstructured and Modular programming approach

In this article I will try to explain about Structured, Unstructured and Modular programming approaches.

Introduction

Usually people start learning programming by writing simple and small programs. They usually write all logics at one place. This practice starts creating problems when program size gets bigger like duplicacy, redundancy, maintenance etc. To overcome this several approach came into light to make this efficient. In this article I will discuss few of those approaches.

Unstructured Programming approach

What we saw above was nothing but an example of unstructured programming style. In this approach programmer put all their code in one place or say in one program. There is no harm as such but when line of code increases, situation starts getting unmanageable. A programmer can face so many problems like:
  • Duplicacy and redundancy of code
  • Code maintenance problem
  • Readability and many more
This approach is totally useless if working on a large project. It can be only helpful while testing one or two features etc.

Structured Programming approach

To overcome above situation it was needed to come up with a structured approach to make some code separation keeping reusability in mind. So the next approach was Structured Programming or Procedure Oriented Programming (POP) approach. In this approach a new idea came up and a set of execution code was keep in a place and it was called function.
Program was divided into separate functions which was easier to manage and re-use as compared to unstructured approach. This was very helpful from reusability point of view but still all code was in same place so still there was a problem to manage them.

Modular Programming approach

A new idea came into light and common functionalities was grouped into modules. This approach helped in dividing programs into small parts called modules. This approach was really helpful. All was good except one. All modules can have their own data and also they were capable to maintain their internal state. But this came as a problem because there can be only one state per module so each module exists at most once in a program.
All the above approach was good enough in their own scope but still there was a need for something else which may be really helpful in making programmer's life easier. And a new approach came which we popularly knows as Object Oriented Programming System (OOPS). This is really great and is using world wide these days by programmers. Hope this article helped you a lot.

Fetch URL as Google in Google web master tool

You can use Web Master's fetch as google option to add your urls in google crawl. In this article I will explain about how to add your website url manually in google indexing system without waiting for google crawler.

Introduction

You can request google crawl to fetch your url on demand using this facility.

Step by Step

Let's see this step by step

Step 1: Open google web master tool and select your website

Step 2: Click on Crawl > Fetch as Google

Step 3: Enter your url and click on fetch

Step 4: When status is complete click on Submit to Index.

Hope this helps you.