Navigation

Search

Categories

On this page

Hiding a Submit Button When Clicked Using Javascript
Microsoft AJAX Content Delivery Network (CDN)
Passing a Value from Javascript to ASP.NET (Client to Server)
Accessing Controls Using Javascript
Using jQuery to Change the Background Color of Rows on Hover
Check/Uncheck all Items in an ASP.NET CheckBox List using jQuery
Check/Uncheck All Checkboxes in a GridView
Make your own AJAX "loading" icons
Using the Timer Control With an UpdatePanel - Part 2.
Using the Timer Control With an UpdatePanel
Cascading Dropdown Boxes with AJAX
Add Javascript to an ASP.NET Page
Sharing Client-Side Code with Server-Side Code
Using Javascript with ASP.NET
Why ASP.NET AJAX UpdatePanels are dangerous
AJAX Tab control: Tabs display incorrectly in IE7
Using the AJAX Control Toolkit in Sharepoint
Using XMLHttpRequest
Google AJAX Search API
Javascript/AJAX Library
AJAX-Style Loading Icons
Saving an Array to a Database
AJAX: Populating a selectbox with results from a database

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 240
This Year: 46
This Month: 3
This Week: 0
Comments: 0

Sign In
Pick a theme:

# Wednesday, January 06, 2010
Wednesday, January 06, 2010 6:57:11 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | HTML | Javascript/AJAX )


 

This is a cool trick which assigns a bit of javascript to a server-side button to hide one button and replace it with another. In this example, the submit button, chkReview, when clicked is hidden from the user and is replaced with another button, btnSaveDisabled, which says “Please wait…Your request is being processed.”

 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)   
If Not Page.IsPostBack Then
chkReview.OnClientClick = string.Format("javascript:{0}.style.visibility = 'hidden';{0}.style.display  = 'none';{1}.style.visibility = 'visible'", 
chkReview.ClientID, btnSaveDisabled.ClientID) End If End Sub
<asp:Button ID="chkReview" runat="server" onclick="chkSubmitRequest_Click" Text="Submit Request" CssClass="button"  />
<br />
<asp:Button ID="btnSaveDisabled" Enabled="false" runat="server" Text="Please wait...Your request is being processed" 
Style="visibility: hidden;" CssClass="button" />
 
Comments [0] | | # 
# Thursday, September 17, 2009
Thursday, September 17, 2009 4:03:55 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET AJAX | Javascript/AJAX | jQuery )


http://www.asp.net/ajax/CDN/

Here is a working demo of this code example

<!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>
        <title>jQuery from Microsoft AJAX CDN</title>
        <script src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>

        <script type="text/javascript">
        
        $( domReady );
        
        function domReady() {
            $('#btn').click( showMessage );
        }
        
        function showMessage() {
            $('#message').fadeIn('slow');
        }
        
        </script>
    </head>
    <body>

    <button id="btn">Show Message</button>

    <div id="message" style="display:none">

        <h1>Hello from jQuery!</h1>

    </div>

    </body>
    </html>

 
 
 
Comments [0] | | # 
# Wednesday, July 15, 2009
Wednesday, July 15, 2009 7:18:07 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX | jQuery )


This comes up a lot for me when I need to juggle client side and server side values back and forth.  In this example, I will create and set the values on the client side using javascript and then demonstrate how to read those values on the server side using ASP.NET.  To do this we need to follow these steps:

  • Create a HTML hidden field on the page
  • Set the value(s) using javascript
  • Read those values on the server side

The first thing I did was create a repeater control and within the ItemTemplate place a checkbox which contains the value we’re interested in – in this case id_individual.  Notice that the checkboxes have a class value of “DirectorName” which we’ll use in our jQuery next. Next to the checkbox we list the person’s name in label controls. 

<asp:Repeater id="rptDirectors" DataSourceID="dsDirectors" Runat="Server">  
  <ItemTemplate>
      <input type="checkbox" value='<%# Container.DataItem("id_individual") %>' id="chkDirectorName" name="chkDirectorName" runat="Server" class="DirectorName" checked />
      <asp:Label ID="Label1" Text='<%# Eval("DirFName") %>' Runat="Server"/>  <asp:Label ID="Label2" Text='<%# Eval("DirLName") %>' Runat="Server"/><br />      
   </ItemTemplate> 
</asp:Repeater>    

We also need our hidden client-side field which will hold our id_individual values. Notice that it has a runat=”server” property.  This is what makes it accessible to both the client and server sides of this equation. We will also create a asp:Literal control which will show us the value on the server side after the value has been passed to the server side.

<input id="lblCheckedDirs" name="lblCheckedDirs" type="Hidden" runat="server" visible="true" />

<asp:Literal ID="lblServerSideValue" runat="server" Visible="true" />

Next, we will create a javascript function named getDirectorIDs to get the value of each checked checkbox inside of the repeater control rptDirectors.  Using the jQuery library makes it very easy to iterate over the checkboxes to get these values.  We place the comma delimited values into a variable named result. We then place the value of result into the hidden control, lblCheckedDirs.  

<script language="Javascript" type="text/javascript">
    // this gets all of the director id_individual values
    $(document).ready(function getDirectorIDs() {    
        var result = "";
        $(".DirectorName:checked").each(function() {
            result = result + $(this).val() + ",";
        });
        // place the selected id_individual values in the label control lblCheckedDirs
        document.getElementById('lblCheckedDirs').value = result;
    }); 
</script>

Next, our submit button calls both the client side function getDirectorIDs() as well as our server side function btnContinue_Click.  getDirectorIDs populates the client-side hidden control, lblCheckedDirs, and btnContinue_Click populates the server literal control, lblServerSideValue.

<asp:Button ID="btnContinue" runat="server" Text="Continue >>" OnClientClick="getDirectorIDs();" onclick="btnContinue_Click" />    
<script runat="server">
    Protected Sub btnContinue_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        lblServerSideValue.Text = lblCheckedDirs.Value
    End Sub
</script>

Here is the source code for the whole page. 

Comments [0] | | # 
# Wednesday, June 03, 2009
Wednesday, June 03, 2009 10:16:30 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX )

 

You can get the values for form controls on the client side using javascript using a method like this:

var label = document.getElementById("<%=Label1.ClientID%>"); 

If the control is inside another control like a FormView or a GridView then you can use this method:

var label = document.getElementById('<%= FormView1.FindControl("Label1").ClientID %>');
Comments [0] | | # 
# Wednesday, December 31, 2008
Wednesday, December 31, 2008 3:47:52 AM (GMT Standard Time, UTC+00:00) ( Javascript/AJAX | jQuery )

Another example of how cool jQuery is.

Here is a working example

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
    Sub Page_Load()

        If Not Page.IsPostBack Then       
            BindGridView()
        End If

    End Sub
    
    Sub BindGridView()
        
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString)
        Dim strSqlText As String = "SELECT Title, Director FROM Movies"

        Dim cmd As New SqlCommand(strSqlText)
        con.Open()
        cmd.Connection = con

        dgMovies.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        dgMovies.DataBind()

        con.Close()
        con.Dispose()
        
    End Sub   
           
</script>

<html>
<head><title></title>
<script type="text/javascript" src="jquery/jquery-1.2.6.min.js"></script>

    <script type="text/javascript">         
         $(document).ready(function() {        
            $("#dgMovies tr").css({ background: "F7F6F3" }).hover(
                function() { $(this).css({ background: "#C1DAD7" }); },
                function() { $(this).css({ background: "#F7F6F3" }); }
                );
        });
    </script>
    
</head>
<body>

<form runat="server">

<asp:gridview runat="server" CellPadding="4" 
ForeColor="#333333" GridLines="None" 
AllowSorting="false" 
id="dgMovies" Width="80%" 
HorizontalAlign="Center" 
Font-Names="Tahoma" 
Font-Size="Small" 
EmptyDataText="No records were found">
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />    
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="Blue" Font-Bold="True" ForeColor="Black" />
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:gridview>

</form>

</body>
</html>
Comments [0] | | # 
Wednesday, December 31, 2008 3:21:57 AM (GMT Standard Time, UTC+00:00) ( Javascript/AJAX | jQuery )

There are many ways to check/uncheck a list of checkboxes using javascript or even in ASP.NET such as in a Gridview.  Using jQuery is probably one of the easiest and most elegant solutions I've found.  Here is an example of how to do it.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If (Not Page.IsPostBack) Then
            cb1.Items.Add(New ListItem("Items 1", "Items 1"))
            cb1.Items.Add(New ListItem("Items 2", "Items 2"))
            cb1.Items.Add(New ListItem("Items 3", "Items 3"))
            cb1.Items.Add(New ListItem("Items 4", "Items 4"))
            cb1.Items.Add(New ListItem("Items 5", "Items 5"))
        End If
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-1.2.6.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function() {
            $('#chkAll').click(
             function() {
                 $("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
             });
         });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBox ID="chkAll" runat="server" Text="Check All" /><br />
        <asp:CheckBoxList ID="cb1" runat="server">
        </asp:CheckBoxList>
    </div>
    </form>
</body>
</html>

Here is another example which I think is a little simpler than the one above

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Access Values From Multiple or Selected ASP.NET TextBoxes</title>

<script src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>

<script type="text/javascript">
$(function() {
    var $chkBox = $("input:checkbox[id$=chkAll]");
    var $tblChkBox = $("table.chk input:checkbox");
        
        $chkBox.click(function() {
            $tblChkBox
            .attr('checked', $chkBox
            .is(':checked'));
        });
        
        // Unchecks chkAll when a checked CheckBox in cbList is unchecked
        
        $tblChkBox.click(
        function(e) {
            if (!$(this)[0].checked) {
            $chkBox.attr("checked", false);
        }
    });
});
</script>
</head>
<body>
<form id="form1" runat="server">

<asp:CheckBox ID="chkAll" runat="server" Text="Check All" ToolTip="Click here to check/uncheck all checkboxes at once"/>
<br /><hr />
    <asp:CheckBoxList ID="cbList" runat="server" class="chk">
        <asp:ListItem Text="Option A" Value="A" />
        <asp:ListItem Text="Option B" Value="B" />
        <asp:ListItem Text="Option C" Value="C" />
        <asp:ListItem Text="Option D" Value="D" />
        <asp:ListItem Text="Option E" Value="E" />
    </asp:CheckBoxList>
<br />

</form>
</body>
</html>
Comments [0] | | # 
# Wednesday, May 14, 2008
Wednesday, May 14, 2008 2:22:37 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | Javascript/AJAX )

Having the ability to check or uncheck all of the checkboxes which appear inside of a GridView is a frequent requirement.  There are several javascript libraries which will handle this on the client-side which is usually the better way to go, but this can also be done server-side and along with an AJAX UpdatePanel can be pretty elegant.  Here is a working demo.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
       
    Protected Sub MasterCheck_Click(ByVal sender As Object, ByVal e As CommandEventArgs)
        'Enumerate each GridViewRow
        For Each gvr As GridViewRow In GridView1.Rows
            'Programmatically access the CheckBox from the TemplateField
            Dim cb As CheckBox = CType(gvr.FindControl("Checkbox1"), CheckBox)
            
            Select Case e.CommandName

                Case "Check"
                    'Check all of the checkboxes
                    cb.Checked = True
                    'Change the CommandName, CommandArgument and Text of the button
                    btnMasterCheck.CommandName = "Uncheck"
                    btnMasterCheck.CommandArgument = "Uncheck"
                    btnMasterCheck.Text = "Uncheck All"
                Case "Uncheck"
                    'Uncheck all of the checkboxes
                    cb.Checked = False
                    'Change the CommandName, CommandArgument and Text of the button
                    btnMasterCheck.CommandName = "Check"
                    btnMasterCheck.CommandArgument = "Check"
                    btnMasterCheck.Text = "Check All"
                Case Else

            End Select
        Next
    End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Check/Uncheck All Checkboxes in a GridView</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:SqlDataSource
        id="srcMovies"
        ConnectionString='<%$ ConnectionStrings:MyDatabase %>'
        SelectCommand="SELECT Title, Director FROM Movies ORDER BY Title"
        Runat="server" />
        
        <asp:ScriptManager id="sm1" runat="server" />

    <asp:UpdatePanel id="UpdatePanel1" Runat="server">
   
    <ContentTemplate>
        <asp:GridView ID="GridView1" runat="server" DataSourceID="srcMovies" AutoGenerateColumns="False">
        <Columns>
         <asp:TemplateField HeaderText="">
                 <ItemTemplate>
                    <asp:Checkbox id="Checkbox1" runat="server"  /> 
                 </ItemTemplate>
          </asp:TemplateField> 
         
         <asp:BoundField HeaderText="Title" DataField="Title" />
         <asp:BoundField HeaderText="Director" DataField="Director" />
        </Columns>
        </asp:GridView><br />
        <asp:Button ID="btnMasterCheck" runat="server" CommandName="Check" CommandArgument="Check" OnCommand="MasterCheck_Click" Text="Check All" />
    </ContentTemplate>
    </asp:UpdatePanel>
    
    </div>
    </form>
</body>
</html>
Comments [0] | | # 
# Wednesday, May 07, 2008
Wednesday, May 07, 2008 6:41:45 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX )
# Tuesday, April 29, 2008
Tuesday, April 29, 2008 5:49:27 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | Javascript/AJAX )

In the previous example, Using a Timer Control With an Update Panel, we just refreshed a panel from data in a list.  In this more practical example, we pull the data from a live database which refreshes an UpdatePanel and an AJAX script manager.  Here is a working demo.

<%@ Page Language="vb" %>
<!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 id="Head1" runat="server">
    <title>Timer Movies</title>
    <style type="text/css">
    
    .message
    {
        margin-left: 20px;
        font-style:italic;
    }
    
    </style>
</head>
<body>
    <form id="form1" runat="server">
    
    <asp:ScriptManager ID="sm1" runat="server" />
    
    <asp:Timer ID="Timer1" Interval="5000" runat="server" />
    
    <asp:UpdatePanel ID="up1" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
    </Triggers>
    <ContentTemplate>
    Last Refresh <%= DateTime.Now.ToString("T") %><hr />
    <asp:ListView
        id="lstMovies"
        DataSourceID="srcMovies"
        Runat="server">
        <LayoutTemplate>
            <div id="itemPlaceholder" runat="server">
            </div>
        </LayoutTemplate>
        <ItemTemplate>
            <div>
                Movie Title: <%# Eval("Title") %><div class="message">
                Director: <%# Eval("Director") %></div>
            </div>    
        </ItemTemplate>
    </asp:ListView>    
    </ContentTemplate>      
    </asp:UpdatePanel>
    
    <asp:ObjectDataSource
        id="srcMovies"
        TypeName="Message"
        SelectMethod="Select"
        Runat="server" />
    
    </form>
</body>
</html>

*** Message.vb ***
Imports System
Imports System.Collections
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Configuration

Public Class Message

    Private _Title As String

    Public Property Title() As String
        Get
            Return _Title
        End Get
        Set(ByVal value As String)
            _Title = value
        End Set
    End Property

    Private _Director As String

    Public Property Director() As String
        Get
            Return _Director
        End Get
        Set(ByVal value As String)
            _Director = value
        End Set
    End Property


    Public Shared Function [Select]() As ArrayList
        Dim results As New ArrayList()
        Dim conString As String = WebConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString
        Dim commandText As String = "SELECT Title, Director FROM Movies ORDER BY Id DESC"
        Dim con As New SqlConnection(conString)
        Dim cmd As New SqlCommand(commandText, con)
        Using con
            con.Open()
            Dim reader As SqlDataReader = cmd.ExecuteReader()
            While reader.Read()
                results.Add(New Message(reader))
            End While
        End Using
        Return results
    End Function

    Public Sub New(ByVal reader As SqlDataReader)
        Title = CType(reader("Title"), String)
        Director = CType(reader("Director"), String)
    End Sub

End Class
 
Comments [0] | | # 
Tuesday, April 29, 2008 3:55:25 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | Javascript/AJAX )

This is an interesting example on how to use the Timer control inside of an UpdatePanel to refresh part of a page with no user intervention.   Here is a working demo.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Collections.Generic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected sub Page_Load(sender as object, e as EventArgs)
        dim quotes as new List(of string)()
        quotes.Add("A fool and his money are soon parted")
        quotes.Add("A penny saved is a penny earned")
        quotes.Add("An apple a day keeps the doctor away")
        
        dim rnd as new Random()
        lblQuote.Text = quotes(rnd.Next(quotes.Count))
    end sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Timer Quote</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    
    <asp:Timer ID="Timer1" Interval="2000" runat="server" />

    Page Time: <%= DateTime.Now.ToString("T") %>
    
    <fieldset>
    <legend>Quote</legend>
    <asp:UpdatePanel ID="up1" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
    </Triggers>
    <ContentTemplate>
        <asp:Label ID="lblQuote" runat="server" />
    </ContentTemplate>
    </asp:UpdatePanel>
    </fieldset>
        
    </div>
    </form>
</body>
</html>
Comments [0] | | # 
# Wednesday, April 23, 2008
Wednesday, April 23, 2008 6:28:28 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | Javascript/AJAX )


Making the selections in a dropdownbox dependent upon the selected item in another one is a pretty simple task. Here is a working demo.

<%@ Page Language="VB" %>
<!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 id="Head1" runat="server">
    <title>Cascading DropDownList Controls With AJAX</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:ScriptManager
        id="sm1"
        Runat="server" />

    <asp:UpdatePanel
        id="UpdatePanel1"
        Runat="server">
   
    <ContentTemplate>
        
    <asp:Label
        id="lblTitle"
        Text="Title:"
        AssociatedControlID="ddlTitle"
        Runat="server" />
    <asp:DropDownList
        id="ddlTitle"
        DataSourceID="srcTitle"
        DataTextField="Title"
        DataValueField="Title"
        AutoPostBack="true"
        Runat="server" />
    <asp:SqlDataSource
        id="srcTitle"
        ConnectionString='<%$ ConnectionStrings:MyDatabase %>'
        SelectCommand="SELECT Title FROM Movies ORDER BY Title"
        Runat="server" />
    
    <br /><br />

    
    <asp:Label
        id="Label1"
        Text="Director:"
        AssociatedControlID="ddlDirector"
        Runat="server" />
    <asp:DropDownList
        id="ddlDirector"
        DataSourceID="srcDirector"
        DataTextField="Director"
        AutoPostBack="true"
        Runat="server" />
    <asp:SqlDataSource
        id="srcDirector"
        ConnectionString='<%$ ConnectionStrings:MyDatabase %>'
        SelectCommand="SELECT Director FROM Movies WHERE Title=@Title ORDER BY Title"
        Runat="server">
        <SelectParameters>
            <asp:ControlParameter Name="Title" ControlID="ddlTitle" />
        </SelectParameters>
    </asp:SqlDataSource>    
    
    </ContentTemplate>
    </asp:UpdatePanel>    
    
    </div>
    </form>
</body>
</html>
Comments [0] | | # 
# Thursday, April 10, 2008
Thursday, April 10, 2008 4:32:18 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | Javascript/AJAX )

There are several ways to add client-side javascript to a ASP.NET page depending on your needs.  Other than using the traditional method of just adding a <script> section in the <head> section of the page, but what if want to reference that javascript across multiple pages?  Here are a few other methods.

Using an external .js file

You could just reference an external .js file like this:

<script language="javascript" src="scroller.js"></script>

 

Using a master page

This approach uses the ClientScriptManager to register a client-side script in a master page and makes it accessible across the whole site.

--masterpage.master

<%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %>
<!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 onload="displayTime()">
  <form id="form1" runat="server">
    <div>
      <div>
        HEADER
        <div id="currentTime">
        </div>
      </div>
      <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
      </asp:ContentPlaceHolder>
    </div>
  </form>
</body>
</html>

--MasterPage.master.vb

Partial Class MasterPage
    Inherits System.Web.UI.MasterPage

  Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
    LoadScript()
  End Sub

  Private Sub LoadScript()

    Dim scriptName As String = "DisplayTime"
    Dim scriptUrl As String = "~/Scripts/DisplayTime.js"
    Dim scriptType As Type = Me.GetType()

    Dim clientScriptManager As ClientScriptManager = Page.ClientScript

    If (Not clientScriptManager.IsClientScriptIncludeRegistered(scriptType, scriptName)) Then
      clientScriptManager.RegisterClientScriptInclude(scriptType, scriptName, ResolveClientUrl(scriptUrl))
    End If

  End Sub
End Class
 

Build the javascript as a string and register it

Rather than reference an external javascript file, you can use the RegisterClientScriptBlock method along with the StringBuilder method to register some javascript in your page.
 
<%@ Page Language="VB" AutoEventWireup="false"
  CodeFile="Default3.aspx.vb" Inherits="Default3" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  <div>
    <input type="button" value="Change Color" onclick="changeColor('blue')" />
  </div>
</asp:Content>
 
Partial Class Default3
    Inherits System.Web.UI.Page

  Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
    LoadScript()
  End Sub

  Private Sub LoadScript()

    Dim clientScriptManager As ClientScriptManager = Page.ClientScript
    Dim sb As StringBuilder = New StringBuilder()

    sb.Append("<script language='javascript'>")
    sb.Append("function changeColor(color) {")
    sb.Append("document.bgColor=color;")
    sb.Append("}")
    sb.Append("<")
    sb.Append("/script>")

    If (Not clientScriptManager.IsClientScriptBlockRegistered("ColorScript")) Then
      clientScriptManager.RegisterClientScriptBlock(Me.GetType(), "ColorScript", sb.ToString())
    End If

  End Sub
End Class
 

Build the javascript as a string and register it on startup

Lastly, using the same approach as above except for this time the javascript doesn't get registered until the page starts using the RegisterStartupScript method

 
Partial Class Default4
    Inherits System.Web.UI.Page

  Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
    LoadScript()
  End Sub

  Private Sub LoadScript()

    Dim clientScriptManager As ClientScriptManager = Page.ClientScript
    Dim sb As StringBuilder = New StringBuilder()

    sb.Append("<script language='javascript'>")
    sb.Append("document.bgColor='green';")
    sb.Append("<")
    sb.Append("/script>")

    If (Not clientScriptManager.IsStartupScriptRegistered("ColorScript")) Then
      clientScriptManager.RegisterStartupScript(Me.GetType(), "ColorScript", sb.ToString())
    End If


  End Sub

End Class
Comments [0] | | # 
# Friday, April 04, 2008
Friday, April 04, 2008 7:41:59 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | Javascript/AJAX )


I often come across the need to share data between javascript client-side code and my asp.net server controls.  Many functions just perform better on the client-side and the need to pass data from my server controls to javascript comes up often.  One of the easier ways of doing this is to create a asp:hiddenfield. Doing this gives your javascript code access to the data it contains.  In this example, we programatically create a asp:Hiddenfield with a ID="sharedData" and assign a value of "New client initial value." When we click the server-side button, btnGetData which calls the javascript function getSharedData(), it passes the hiddenfield value from sharedData to getSharedData().

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="Default" %>

<!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>
    <script type="text/javascript">
    function getSharedData()
    {
        alert("Shared data is " + document.getElementById("sharedData").value + ".");
    }
    
    </script>    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
        <asp:Button ID="btnGetData" runat="server" Text="Get Data" OnClientClick="getSharedData()" />
    </form>
</body>
</html>
Code behind - Default.aspx.vb:
Partial Class Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreLoad
        Dim hiddenField As System.Web.UI.WebControls.HiddenField = New System.Web.UI.WebControls.HiddenField
        hiddenField.ID = "sharedData"
        hiddenField.Value = "New client initial value"

        Page.Form.Controls.Add(hiddenField)
    End Sub
End Class
Comments [0] | | # 
# Thursday, March 20, 2008
Thursday, March 20, 2008 7:53:14 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | Javascript/AJAX )

I've been working on a project which required the use of some javascript with some server-side controls. I spent considerable time monkeying around with the Page.ClientScript.RegisterClientScriptBlock() method which registers a client script on the page. I couldn't quite get it right using this method and ended up with a much simpler approach anyway.  Every server-side web control has an "Add" method which you can use when the page loads.   In the example below, I register a click event for a button and 2 different textboxes.  Take notice that for the textboxes I use the client side id value for them (e.g. 'Header1_txtFirstName').  These values can be obtained by looking at the source code of the page in the browser.

Private Sub Page_Load(ByVal Src As Object, ByVal E As EventArgs)
        If Not Page.IsPostBack Then
            btnDelete.Attributes.Add("onClick", "return confirm('You sure you want to delete the record?');")
            txtFirstName.Attributes.Add("onClick", "document.getElementById('Header1_txtFirstName').value = '';")
            txtLastName.Attributes.Add("onClick", "document.getElementById('Header1_txtLastName').value = '';")
        End If
End Sub
Candidate Name: 
<asp:TextBox ID="txtFirstName" runat="server" Text="First Name" /> 'this becomes Header1_txtFirstName
<asp:TextBox ID="txtLastName" runat="server" Text="Last Name" /> 'this becomes Header1_txtLastName
More information on this topic here: http://dotnetslackers.com/articles/aspnet/JavaScript_with_ASP_NET_2_0_Pages_Part1.aspx
Comments [0] | | # 
# Sunday, January 13, 2008
Sunday, January 13, 2008 4:04:30 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | Javascript/AJAX )

An interesting article on the drawbacks of using the UpdatePanel

http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/

Comments [0] | | # 
# Tuesday, October 23, 2007
Tuesday, October 23, 2007 2:09:26 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX | Sharepoint )

I was experimenting with the AJAX Tab control extender which is part of ASP.NET AJAX Control Toolkit in Sharepoint.  The bottom part of the tabs was being cut off for no apparent reason.  When I would run the page locally, it would render fine but within Sharepoint, the text on the tabs was being cut off on the bottom. After several frustrating hours, I found out how to fix the CSS that was causing the problem.

After looking at the Tabs.css file, it appears that the right hand graphic on the tab control is set to a height of 21px. The tab itself with the text has a height of 13px. This can be remedied by modifying the xp theme to look like this:

.ajax__tab_xp .ajax__tab_tab {height:21px;padding:4px;margin:0;background:url(<%=WebResource("AjaxControlToolkit.Tabs.tab.gif")%>) repeat-x;}

The Tabs.css file can be found in the AJAX Control Toolkit (with source code).  I changed the CSS used by my particular theme which in my case was /_themes/Wheat/Whea101165001.css


.ajax__tabs .ajax__tab_header {font-family:verdana,tahoma,helvetica;font-size:11px;background-color:#EEE8AA;background:url("/it/images/tabs/tab-line.gif");background-repeat:repeat-x;background-position:bottom;}
.ajax__tabs .ajax__tab_outer {background:url("/it/images/tabs/tab-right.gif");background-repeat:no-repeat;background-position:right;height:21px;}
.ajax__tabs .ajax__tab_inner {padding-left:3px;background:url("/it/images/tabs/tab-left.gif");background-repeat:no-repeat;}

/* remove this line
.ajax__tabs .ajax__tab_tab {height:13px;padding:4px;margin:0;background-color:#EEE8AA;background:url("/it/images/tabs/tab.gif");background-repeat:repeat-x;}
*/

/* Add this one */
.ajax__tabs .ajax__tab_tab {height:21px;padding:4px;margin:0;background:url("/it/images/tabs/tab.gif") repeat-x;}

.ajax__tabs .ajax__tab_body {font-family:verdana,tahoma,helvetica;font-size:10pt;border:1px solid #999999;border-top:0;padding:8px;background-color:#EEE8AA;}
.ajax__tabs .ajax__tab_hover .ajax__tab_outer {background-color:#EEE8AA;background:url("/it/images/tabs/tab-hover-right.gif");background-repeat:no-repeat;background-position:right;}
.ajax__tabs .ajax__tab_hover .ajax__tab_inner {background-color:#EEE8AA;background:url("/it/images/tabs/tab-hover-left.gif");background-repeat:no-repeat;}
.ajax__tabs .ajax__tab_hover .ajax__tab_tab {background-color:#EEE8AA;background:url("/it/images/tabs/tab-hover.gif");background-repeat:repeat-x;}
.ajax__tabs .ajax__tab_active .ajax__tab_outer {background-color:#EEE8AA;background:url("/it/images/tabs/tab-active-right.gif");background-repeat:no-repeat;background-position:right;}
.ajax__tabs .ajax__tab_active .ajax__tab_inner {background-color:#EEE8AA;background:url("/it/images/tabs/tab-active-left.gif");background-repeat:no-repeat;}
.ajax__tabs .ajax__tab_active .ajax__tab_tab {background-color:#EEE8AA;background:url("/it/images/tabs/tab-active.gif");background-repeat:repeat-x;}

Also, by default, the CssClass used by the Tabcontrol is .ajax__tabs_xp.  I changed mine to use .ajax__tabs so it would use the changed Css /_themes/Wheat/Whea101165001.css rather than the CSS used by the Tabcontrol.

Other resources that helped with this issue:

 

Comments [0] | | # 
# Sunday, October 21, 2007
Sunday, October 21, 2007 3:39:07 AM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX | Sharepoint )

I recently tried adding a page to WSS 3.0 which utilized one of the ASP.NET AJAX components and received the error "Error - this control is not registered as a safe control." After some digging, I found out that you have take a few steps to get these AJAX control extenders to work in Sharepoint.

  • AjaxControlToolkit.dll - Put this in your /Bin directory
  • Add an assembly reference in the web.config (note: for the future versions of the Control Tookit, the version number can change.  Right-click on the dll and go to properties to find the dll verison):

   <assemblies>
   ...
   <add assembly="AjaxControlToolkit, Version=1.0.10920.32880, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
   ....
   </assemblies>

  • Add the tagprefix for the Control Toolkit in the web.config:

    <controls>
    ...
    <add namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" tagPrefix="ajaxToolkit"/>
    ....
    </controls>

  • Register the assembly as a safe control:  

<SafeControls>

<SafeControl Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TypeName="*" Safe="True" />
<SafeControl Assembly="AjaxControlToolkit, Version=1.0.10920.32880, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e" Namespace="AjaxControlToolkit" TypeName="*" Safe="True" />

</SafeControls>

That's it.  You can now start using all of those control AJAX extenders in Sharepoint

 

Comments [0] | | # 
# Tuesday, July 03, 2007
Tuesday, July 03, 2007 6:48:50 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX )

A coworker passed along this link from IBM which provides a nice series of tutorials on AJAX. The example below is a classic example of how to use the XMLHTTPRequest object while checking for different browser types and then using the server's response for something.

<script language="javascript" type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}

if (!request)
alert("Error initializing XMLHttpRequest!");

function getCustomerInfo() {
var phone = document.getElementById("phone").value;
var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}

function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText.split("|");
document.getElementById("order").value = response[0];
document.getElementById("address").innerHTML = response[1].replace(/\n/g, "<br />");
} else if (request.status == 404) {
alert ("Requested URL is not found.");
} else if (request.status == 403) {
alert("Access denied.");
} else
alert("status is " + request.status);
}
}

</script>

<body>
<p><img src="breakneck-logo_4c.gif" alt="Break Neck Pizza" /></p>
<form action="POST">
<p>Enter your phone number:
<input type="text" size="14" name="phone" id="phone"
onChange="getCustomerInfo();" />
</p>
<p>Your order will be delivered to:</p>
<div id="address"></div>
<p>Type your order in here:</p>
<p><textarea name="order" rows="6" cols="50" id="order"></textarea></p>
<p><input type="submit" value="Order Pizza" id="submit" /></p>
</form>
</body>

Comments [0] | | # 
# Monday, July 02, 2007
Monday, July 02, 2007 5:48:54 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX )

Google makes a cool API that utilizes AJAX to which allows developers to add a Web or local search to their sites relatively easily. 

I created an example of it here: http://www.stonecoastwebdesign.com/search/example.htm

Comments [0] | | # 
Monday, July 02, 2007 3:37:01 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX )

A co-worker passed this along to me which looks pretty cool

http://extjs.com/

Comments [0] | | # 
# Monday, June 25, 2007
Monday, June 25, 2007 5:52:42 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX )

Some useful icons for displaying those "loading" messages used in AJAX-enabled applications.

 

Comments [0] | | # 
# Thursday, June 07, 2007
Thursday, June 07, 2007 5:54:16 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET | Javascript/AJAX )

I really like this example because it illustrates just how powerful client-side and server-side technology used in conjunction can be.  My javascript function, saveSelectedtoDatabase, passes a few parameters to my .aspx page saveSelected.aspx.  The string passed is in the form saveSelected.aspx?UserID=2447&BenchmarkName=Benchmark1&CompanyName=IBM*Ford Motor*AMD&CompID=14575*17411*41522

function savedSelectedtoDatabase(intUserID,benchmarkName,thistext,thisvalue)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support the XMLHttpRequest object.")
return
}
var url="saveSelected.aspx?UserID="+intUserID+"&BenchmarkName="+benchmarkName+"&CompanyName="+thistext+"&CompID="+thisvalue;
xmlHttp.onreadystatechange=stateChanged5
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

 

saveSelected.aspx takes the querystring value passed to it and splits the CompanyName and CompID values by * and then saves each record to a SQL Server database.

<script runat="server">

Sub Page_Load()
If Not IsPostBack Then

Dim intUserID As Integer
Dim strBenchmarkName As String
Dim strCompID As String
Dim strCompanyName As String

'These values are coming from the AJAX function savedSelectedtoDatabase()
intUserID = Request.QueryString("UserID")
strBenchmarkName = Request.QueryString("BenchmarkName")
strCompID = Request.QueryString("CompID")
strCompanyName = Request.QueryString("CompanyName")

'Remove trailing * characters
strCompID = strCompID.Substring(0, strCompID.Length - 1)
strCompanyName = strCompanyName.Substring(0, strCompanyName.Length - 1)

'Place these values into an array
Dim arrCompID As String() = Nothing
arrCompID = strCompID.Split("*")

Dim arrCompanyName As String() = Nothing
arrCompanyName = strCompanyName.Split("*")

'Get the length of one element of the array so we now how many times
'to loop through the database with updates/inserts
Dim i As Integer
Dim myArrayLength As Integer = (arrCompID.Length - 1)

'Insert new record into TBenchmarker and output parameter as BenchmarkID
'TBenchmarker requires UserID and BenchmarkName

Dim strSQLConn As SqlConnection
Dim cmd As SqlCommand
Dim SqlText As String

strSQLConn = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
            
Try    
strSQLConn.Open()
'Insert new record into TBenchmarker
SqlText = "benchmarkerAddRecord"
cmd = New SqlCommand(SqlText, strSQLConn)
cmd.CommandType = CommandType.StoredProcedure

'input parameters for the sproc
cmd.Parameters.AddWithValue("@UserID", intUserID)
cmd.Parameters.AddWithValue("@BenchmarkName", strBenchmarkName)

'Output parameter from sproc benchmarkerAddRecord which is SCOPE_IDENTITY
'Create a SqlParameter object to hold the output parameter value
Dim intNewBenchmarkID As New SqlParameter("@RETURN_VALUE", SqlDbType.Int)

'Set Direction as Output
intNewBenchmarkID.Direction = ParameterDirection.ReturnValue

'Finally, add the parameter to the Command's Parameters collection
cmd.Parameters.Add(intNewBenchmarkID)

'Execute the sproc
cmd.ExecuteScalar()

'Now you can grab the output parameter's value...
Dim intNewBenchmarkIDValue As Integer = Convert.ToInt32(intNewBenchmarkID.Value)

'Insert new record(s) into TBenchmarkerSaved
For i = 0 To myArrayLength
SqlText = "saveBenchmarkValues"
cmd = New SqlCommand(SqlText, strSQLConn)
cmd.CommandType = CommandType.StoredProcedure

'input parameters for the sproc
'intNewBenchmarkIDValue is the value returned from the sproc benchmarkerAddRecord
cmd.Parameters.AddWithValue("@BenchmarkID", intNewBenchmarkIDValue)
cmd.Parameters.AddWithValue("@CompID", arrCompID(i))
cmd.Parameters.AddWithValue("@CompanyName", arrCompanyName(i))
cmd.ExecuteNonQuery()
Next i
            
strSQLConn.Close()

'This value gets returned back to savedSelectedtoDatabase and added
'as an option to ddlSavedBenchmarks dropdown
Response.Write(strBenchmarkName & "#" & intNewBenchmarkIDValue)

Catch ex As Exception
Response.Write("There was an error when saving these companies. Please try again.")
Finally
        
End Try

End If        
End Sub

</script>

Comments [0] | | # 
# Tuesday, June 05, 2007
Tuesday, June 05, 2007 7:06:17 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX )

I've been working on a project that's involved a lot of javascript and AJAX development.  This basic idea was to call a .aspx page which queried a database, placed the results in an array, returned the array to the client and then split out the array and populated the select box.  This is how I did it.

First create the XMLHTTPObject

function getIndustries()
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support the XMLHttpRequest object.")
return
}

Call getindustries.aspx

var url="getIndustries.aspx"
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

This displays a 'Please Wait message and icon to the user while the transaction is occuring.

function stateChanged()

  if (xmlHttp.readyState == 0)
  {
document.getElementById("lblResults").innerHTML = "<img src='mozilla_blu.gif' alt='loading..please wait'> Please wait"; //loading
  }
  else if(xmlHttp.readyState == 1)
  {
document.getElementById("lblResults").innerHTML = "<img src='mozilla_blu.gif' alt='loading..please wait'> Please wait"; //loaded
  }
  else if(xmlHttp.readyState == 2)
  {
document.getElementById("lblResults").innerHTML = "<img src='mozilla_blu.gif' alt='loading..please wait'> Please wait"; //interactive
  }
  else if(xmlHttp.readyState == 3)
  {
document.getElementById("lblResults").innerHTML = "<img src='mozilla_blu.gif' alt='loading..please wait'> Please wait";
  }
  else if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  {
document.getElementById("lblResults").innerHTML = "";  
 
  // Clear the available listbox of any previous options
  document.choiceForm.available.length = 0; 

// Split the delimited response into an array  
  var s = xmlHttp.responseText;
  var re = new RegExp('{([^{}]*)}','g');
  var x = [];
  while (re.exec(s)){ 
   x.push(RegExp.$1.split('#'));
  }
 
 // Add the array options to the selectbox available
  var sel = document.forms['choiceForm'].elements['available'];
 for (var i=0, len=x.length; i<len; i++){
    sel.options[i] = new Option(x[i][1], x[i][0]);
    }
 
  }
}

function GetXmlHttpObject()
{
  var objXMLHttp=null
 
  try {
    objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP"); //later IE
  } catch (e) {
  try {
    objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); //earlier IE
  } catch (e) {
  objXMLHttp = null;
  }
  }
 
  if (objXMLHttp==null)
  {
    objXMLHttp=new XMLHttpRequest() //IE7, Firefox, Safari
  }
  return objXMLHttp
}

getIndustries.aspx

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>

<script runat="server">
    Sub Page_Load()
        Dim strSQLConn As SqlConnection
        Dim strSqlText As String
        Dim cmd As SqlCommand
        Dim myList As New ArrayList
        Dim dr As SqlDataReader
        Dim count As Integer
        Dim mySB As New StringBuilder()
               
        strSQLConn = New SqlConnection(ConfigurationSettings.AppSettings("CorpLibConnectionStringCurr"))
        strSqlText = "getIndustries"
        cmd = New SqlCommand(strSqlText, strSQLConn)
        cmd.CommandType = CommandType.StoredProcedure
       
        Try
            strSQLConn.Open()
            dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)                       
            
                        
            With dr
                If dr.HasRows Then
                    While dr.Read
                        mySB.Append("{")
                        mySB.Append(dr.GetInt32(0))
                        mySB.Append("#")
                        mySB.Append(dr.GetString(1))
                        mySB.Append("}")
                        count += 1
                    End While
                End If
            End With
           
        Finally
            dr.Close()
            strSQLConn.Close()
        End Try

    Dim strResults As String
    strResults = mySB.ToString().TrimEnd(",".ToCharArray())   
    Response.Write(strResults)
    End Sub


</script>

 

 

Comments [0] | | #