Adding jQuery to ASP.NET controls allows you to further enhance your custom controls. One way to do this is by adding java script to pages and initializing your controls after the page is done loading. Another way is to add the java script to the control in the PreRender method.
Step 1: Add jQuery and jQuery UI Javascript and CSS files to your project.
The jQuery files can be found
here and the jQuery UI files can be found
here, Or you can just download the sample project using the link at the end of this post.
Step 2: Adding References to the .js and .css files.
You can add the references to each page you plan to use your controls on, or if you are using mater pages you can add the references there.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>One More IT Blog</title>
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.10.1.custom.css" />
<link rel="stylesheet" href="Scripts/chosen/chosen.css" />
<script src="Scripts/jquery-1.9.1.js"></script>
<script src="Scripts/jquery-ui-1.10.1.custom.js"></script>
<script src="Scripts/chosen/chosen.jquery.js"></script>
Step 3: Create a class extending the TextBox or the TextBoxReqValidator control created in one of the previous posts.
public class TextBoxReqValidator : TextBoxReqValidator
{
Step 4: OnPreRender
We will register our script in the OnPreRender method. The script attaches the data picker functionality to our text box control.
#region Pre Render
/// <summary>
/// PreRender
/// </summary>
/// <param name="e"></param>
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (Enabled == true)
{
// Check to see if the client script is already registered.
if (!this.Page.ClientScript.IsStartupScriptRegistered(String.Format("jQuery_{0}", this.ClientID)))
{
String script = "$(document).ready(function(){$('#" +
this.ClientID + "').datepicker(); });";
script = "<script type=\"text/javascript\">" + script + "</script>";
this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), String.Format("jQuery_{0}", this.ClientID), script, false);
}
}
}
#endregion
Usage Example:
Markup
<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="DateControlsDemo.aspx.cs" Inherits="CustomControls.DateControlsDemo" %>
<%@ Register Assembly="CustomControls" Namespace="CustomControls.Controls" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<cc1:DatePickerJQ runat="server" Id="DatePickerJQ"></cc1:DatePickerJQ>
<br />
<asp:Button ID="Submit" runat="server" CausesValidation="true" Text="Submit" />
</asp:Content>
Example:
Complete Source:
Demo:
No comments:
Post a Comment