Assign datepicker to runtime/dynamic textboxes in ASP.NET using jQuery

In this short and simple article, we will see how to assign datepicker to runtime textboxes or dynamic textboxes using jQuery in ASP.NET.
Here is code to create three textboxes dynamically (programmatically)
Code behind:

protected void Page_Load(object sender, EventArgs e)
    {
        for (int b = 0; b < 3; b++)
        {
                TextBox txtdate = new TextBox();
                txtdate.ID = "dpicker" + b.ToString();
                txtdate.CssClass = "date";   // class date
                 PlaceHolder1.Controls.Add(txtdate);
            }
    }
&#91;/code&#93;
Here we created three textbox programmatically and assigned <strong>date</strong> to CssClass property of textbox. Now we going to use jQuery UI datepicker plugin to this created textbox class. 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   <link type="text/css" rel="Stylesheet" href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" >
</script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/jquery-ui.min.js" >
</script>
<script type="text/javascript">
    $(function () {
        $(".date").datepicker();
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
               <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    </div>
    </form>
</body>
</html>

For more information about Datepicker, have a look my this article.
Thanks.

Call JavaScript function from an ASP.NET AJAX enabled Content Page

If your content page is wrapped in an ASP.NET AJAX UpdatePanel, then you cannot use the ClientScript.RegisterStartupScript to call a JavaScript function during a partial-page postback. Instead, use the ScriptManager.RegisterStartupScript() method.
protected void Page_Load(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@”“);

ScriptManager.RegisterStartupScript(this, this.GetType(), “ajax”, sb.ToString(), false);

}

Thanks.

Create a SiteMap with ASP.NET

What are Sitemaps?

Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling. In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site.
Sitemap tag definitions

Tag Required? Description
<urlset> Required Encloses all information about the set of URLs included in the Sitemap.
<url> Required Encloses all information about a specific URL.
<loc> Required Specifies the URL. For images and video, specifies the landing page (aka play page, referrer page). Must be a unique URL.
<lastmod> Optional The date the URL was last modifed, in YYYY-MM-DDThh:mmTZD format (time value is optional).
<changefreq> Optional Provides a hint about how frequently the page is likely to change. Valid values are:

  • always. Use for pages that change every time they are accessed.
  • hourly
  • daily
  • weekly
  • monthly
  • yearly
  • never. Use this value for archived URLs.
<priority> Optional Describes the priority of a URL relative to all the other URLs on the site. This priority can range from 1.0 (extremely important) to 0.1 (not important at all).

Does not affect your site’s ranking in Google search results. Because this value is relative to other pages on your site, assigning a high priority (or specifying the same priority for all URLs) will not help your site’s search ranking. In addition, setting all pages to the same priority will have no effect.

Sitemap Example

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://www.ashishblog.com/</loc>
    <lastmod>2012-01-01</lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.8</priority>
  </url>
  <url>
    <loc>http://www.ashishblog.com/about-me/</loc>
    <priority>0.5</priority>
  </url>
</urlset>

First, We need to create table or store procedure to get url from sites.
Here I created on table named GoogleIndexProduct with two column : URl and UpdatedDate
Now I used Following code to generate SiteMap xml file from that created table.
SiteMap.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Xml;
using System.Text;
 
public partial class SiteMap: System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Clear();
            Response.ContentType = "text/xml";
            using (XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("urlset");
                writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
                
                string connect = WebConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(connect))
                    {
                        con.Open();
                        string query = "SELECT [URL],Date FROM [GoogleIndexProduct]";
                        SqlCommand cmd = new SqlCommand(query, con);
                        SqlDataReader dr = cmd.ExecuteReader();
                        while (dr.Read())
                        {
                            writer.WriteStartElement("url");
                            writer.WriteElementString("loc", dr[0].ToString());
                            writer.WriteElementString("lastmod", String.Format("{0:yyyy-MM-dd}", dr[1]));
                            writer.WriteElementString("changefreq", "weekly");
                            writer.WriteElementString("priority", "1.0");
                            writer.WriteEndElement();
                        }
                        con.Close();
                        con.Dispose();
                    }
             
                
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
            }
            Response.End();
           
        }
    }

SiteMap.aspx:
The first thing I did when adding the page to the site was to remove all but the top line of the aspx file. This prevents any html being added to the response and invalidating the xml of the sitemap. All that appears, therefore is:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SiteMap.aspx.cs" Inherits="SiteMap" %>

I then logged into my Google account, and submitted the URL (http://www.ashishblog.com/SiteMap.aspx) for my site map, having tested that it validates against the protocol.

Asp.Net Form Validation Part 2 using JQuery Validation and meta Plugin

In Asp.Net Form Validation using jQuery Validation Plugin article, I explain how to use JQuery Validation Plugin in asp.net form.

Now here I will show you how to use meta plugin with jQuery Validation to validate ASP.NET form. Using Meta plugin we can right rules and message into class attribute of input.

we using same example which we used in previous article.

Step 1:

You need jQuery library, jQuery Validation plugin and meta plugin

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://jquery-multifile-plugin.googlecode.com/svn-history/r16/trunk/jquery.MetaData.js"></script>

Step 2:

 
<form id="form1" runat="server">
<asp:TextBox ID="txtName" runat="server" class="{required:true,messages:{required:'required.'}}" ></asp:TextBox>
<asp:TextBox ID="txtage" runat="server" class="{required:true,number:true,minlength:2, messages:{required:'required.',number: 'number Only!' , minlength:'mininum 2 characters.'}}" ></asp:TextBox>
<asp:TextBox ID="txtEmail" runat="server" class="{required:true, email:true,messages:{required:'required.',email: 'invalid email!' }}"></asp:TextBox>
<asp:TextBox ID="txtPass" runat="server" TextMode="Password"  class="{required:true,messages:{required:'required.'}}"></asp:TextBox>
<asp:TextBox ID="txtRePass" runat="server" TextMode="Password" class="{required:true, equalTo:'#txtPass',  messages:{required:'This field is required.', equalTo:'Value entered in this field should equal to value of Password field.'}}" ></asp:TextBox>
<asp:TextBox ID="txtUrl" runat="server" class="{required:true,url:true,messages:{required:'required.',url:'not vaild url'}}">http://</asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="submit" />
</form>

Step 3:

Use validate() of jQuery validation plugin on asp.net form.

<script type="text/javascript">
        $(document).ready(function () {
        $("#form1").validate();
                                  });
</script>

Group < optgroup > in DropDownList using jQuery C#

In this article I‘ll show you how to create groups in the ASP.NET DropdownList control using JQuery.
In this example we are using JQuery’s native support for wrapping elements into other elements with the help of wrapAll() method. It takes only 1 line of code and we can have the groups created in the HTML. However, the drawback of this approach is the groups will disappear on postback.

For Example, we going to create two groups in Dropdownlist as you see above image.
– LessThanFifty
– GreaterThanFifty

First, we bound Dropdownlist using datatable in Page_Load codebehind

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable table = new DataTable();
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("Number", typeof(int));
            //
            // Here we add five DataRows.
            //
            table.Rows.Add(1,57);
            table.Rows.Add(2, 23);
            table.Rows.Add(3, 99);
            table.Rows.Add(4, 8);
            table.Rows.Add(5, 74);

            DropDownList1.DataSource = table;
            DropDownList1.DataValueField = "ID";
            DropDownList1.DataTextField = "Number";
                        
            DropDownList1.DataBind();
        }
    }

Now We have to create a new attribute for every DropdownList item when Dropdownlist is bound (DropDownList1_DataBound). This new attribute will be used for grouping in the JQuery code.

protected void DropDownList1_DataBound(object sender, EventArgs e)
    {
        foreach (ListItem item in ((DropDownList)sender).Items)
        {
            if (System.Int32.Parse(item.Text ) < 50)
                item.Attributes.Add("classification", "LessThanFifty");
            else
                item.Attributes.Add("classification", "GreaterThanFifty");
        } 
    }

Last we use JQuery WrapAll() method to group two different classification attribute (LessThanFifty and GreaterThanFifty)

<script type="text/javascript">
        
        $(document).ready(function() {
            //Create groups for dropdown list
            $("select#DropDownList1 option[classification='LessThanFifty']").wrapAll("<optgroup label='Less than fifty'>");
            $("select#DropDownList1 option[classification='GreaterThanFifty']").wrapAll("<optgroup label='Greater than fifty'>"); 
        });
    
    </script>

Here is full html page code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 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>Ashish Blog</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript">
        
        $(document).ready(function() {
            //Create groups for dropdown list
            $("select#DropDownList1 option[classification='LessThanFifty']").wrapAll("<optgroup label='Less than fifty'>");
            $("select#DropDownList1 option[classification='GreaterThanFifty']").wrapAll("<optgroup label='Greater than fifty'>"); 
        });
    
    </script>
    <style>
    optgroup
    {
        background-color:Gray ;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <h1>ASP.NET DropdownList with group</h1>
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server" Width="200px"
            ondatabound="DropDownList1_DataBound">
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

Thanks.