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>

Best Tooltip plugin of jQuery -qTip

There are many jQuery Tooltip plugin around and it’s hard to figure it out good one. But after trying out most of them, I found qTip Tooltip very easy.
Here is simple example of qTip (Demo).

Code:

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Tooltip Demo - Ashish's Blog</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.qtip-1.0.0.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(".tooltip").qtip({
            content: ' <b>Ashish</b>.<br/> <b>Patel</b>.',
            position: { corner: { target: 'topMiddle', tooltip: 'bottomMiddle'} },
            style: { name: 'light', tip: 'bottomMiddle', border: { width: 2, radius: 1 }, width: 100 },
            show: { when: { event: 'mouseover'} },
            hide: { when: { event: 'mouseout'} }
        });
    });
</script>
<script type="text/javascript">
    $(document).ready(function () {
        $(".txttooltip").qtip({
            content: ' <b>Enter Name</b>.',
            position: { corner: { target: 'rightMiddle', tooltip: 'leftMiddle'} },
            style: { name: 'dark', tip: 'leftMiddle', border: { width: 2, radius: 1 } },
            show: { when: { event: 'focus'} },
            hide: { when: { event: 'unfocus'} }
        });
    });
</script>
</head>
<body>
I'm <a class="tooltip" href="#">Ashish Patel</a>. 
Name: <input class="txttooltip" type="text" name="firstname" />
</body>
</html>

qTip plugin have many more features than I cove in my post. Have look into qTip developer site and download Qtip from there.

Thanks.

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.

Calling database using jQuery AJAX and ASP.NET

AJAX offers users a seamless way to work with your interface, no waiting for whole pages to load. jQuery has a set of tools to make it super simple to implement. We will walk you through how to use jQuery to communicate databse using jquery’s ajax method in asp.net.

Each example will feature the same requirement, and that is to obtain and display the Customer details relating to a specific CustomerID selected from a DropDownList on a page called Customer.aspx.

Continue reading

How to store and retrieve Image in Database using C# ASP.Net jQuery

In this article, I’ll explain how to store and retrieve Image in Database using C# ASP.Net jQuery. There is many other way to do that but here is the easiest way to do it.
Database:
For this tutorial, I am using following database.

CREATE TABLE [dbo].[tblImage](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[image] [image] NULL,
 CONSTRAINT [PK_tblImage] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

Connection string:
Below is the connection string to connect to the database.

<connectionStrings>
    <add name="TempConnectionString" connectionString="Data Source=ASHISH;Initial Catalog=Temp;Persist Security Info=True;User ID=sa;Password=Temp1234567" providerName="System.Data.SqlClient"/>
</connectionStrings>

Page:
In this tutorial, there one aspx page and one handler.
1. UploadImage.aspx – To Store image into database
2. DisplayImage.aspx – To display image from handler
3. DisplayImage.ashx – To read image from database (Handler)

1. UploadImage.aspx
Upload image
Below HTML Markup of the page, you will notice that I have placed FileUpload to upload image into database.

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

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <strong>Upload Image into database</strong><br />
    <br />
    Select
Image: <asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="butSubmit" runat="server" Text="Submit"
onclick="butSubmit_Click" /><br />
<asp:Label ID="lblStatus" runat="server"></asp:Label>
   <br />
    <br />
    <a href="DisplayImage.aspx">Display Image</a></form>
</body>
</html>

Codebehind:

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.Configuration;

public partial class UploadImge : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void butSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            Byte[] imgByte = null;
            if (FileUpload1.HasFile &amp;&amp; FileUpload1.PostedFile != null)
            {
                HttpPostedFile File = FileUpload1.PostedFile;
                imgByte = new Byte[File.ContentLength];
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            }
            string cs = ConfigurationManager.ConnectionStrings["TempConnectionString"].ConnectionString;
           using( SqlConnection connection = new SqlConnection(cs))
           {
               connection.Open();
               string sql = "INSERT INTO tblImage(image) VALUES(@theImage) SELECT @@IDENTITY";
               using (SqlCommand cmd = new SqlCommand(sql, connection))
               {
                   cmd.Parameters.AddWithValue("@theImage", imgByte);
                   int id = Convert.ToInt32(cmd.ExecuteScalar());
                   lblStatus.Text = String.Format("Image is Uploaded successfully!! and Image ID is {0}", id);
                   cmd.Dispose();
               }
               connection.Close();
               connection.Dispose();
           }
        }
        catch(Exception ex)
        {
            lblStatus.Text = "There was an error" + ex.Message ;
        }
       
    }
}

2. DisplayImage.aspx
display image
Below HTML Markup of the page, you will notice that I have placed jQuery function to display Image from database. You may also notice that I created Img variable and call ReadImage.ashx handler by passing Image ID in scr attribute of Img then append this Img to div.display.

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

<!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></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#Button1").click(function (e) {
                $('.display').text('');   //clean div display
                var ID = $("#txtID").val();
                if (ID.length > 0) {
                    var newImage = $('<img />');
                    newImage.attr('src', 'ReadImage.ashx?id=' + ID); // call handler with id
                    $('.display').append(newImage);
                }
                e.preventDefault();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
     Display Image<br />
    <br />
    Id
    <asp:TextBox ID="txtID" runat="server"></asp:TextBox>
&amp;amp;nbsp;<asp:Button ID="Button1" runat="server" Text="Display" />
    <br />
    <br />
    <div class="display"></div>
    <br />
    <br />
    </form>
</body>
</html>

3. DisplayImage.ashx (Handler)

<%@ WebHandler Language="C#" Class="ReadImage" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;

public class ReadImage : IHttpHandler
{
    
    public void ProcessRequest (HttpContext context) {
        Int32 theID;
        if (context.Request.QueryString["id"] != null)
            theID = Convert.ToInt32(context.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter specified");

        context.Response.ContentType = "image/jpeg";
        Stream strm = DisplayImage(theID);
        byte[] buffer = new byte[2048];
        int byteSeq = strm.Read(buffer, 0, 2048);

        while (byteSeq > 0)
        {
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 2048);
        }
    }
    public Stream DisplayImage(int theID)
    { 
        string cs = ConfigurationManager.ConnectionStrings["TempConnectionString"].ConnectionString;
           using( SqlConnection connection = new SqlConnection(cs))
           {
            string sql = "SELECT image FROM tblImage WHERE id = @ID";
            using (SqlCommand cmd = new SqlCommand(sql, connection))
            {
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Parameters.AddWithValue("@ID", theID);
                connection.Open();
                object theImg = cmd.ExecuteScalar();
                try
                {
                    return new MemoryStream((byte[])theImg);
                }
                catch
                {
                    return null;
                }
                finally
                {
                    cmd.Dispose();
                    connection.Close();
                    connection.Dispose();
                    
                }
            }
        }
        
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

Thanks

Download

[wpdm_file id=5]