Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Archive for the ‘JQuery’ Category

Web Page Loading in Steps – ASP.NET Solution By Petr Pechovic

Posted by Ramani Sandeep on February 23, 2010

The common scenario to reach the desired page on the internet is to write the URL to a browser and press Enter. Basically say the browser asks a server for the requested page. The server builds the page (HTML) and sends the result back to the browser. The browser displays the result to the user and makes HTTP requests to other content like images, etc. Let’s jump back to the stage when the server is building the content of the page. Some parts of the page are usually static data immediately available to use. Another data of the page could be dynamic, either from huge database heavy for calculation or from another server like RSS channel. The point is that some of the data is quickly available and some of the data need time to be loaded. The HTML build by server isn’t sending to the browser until it is completely created. That is obvious.

Read more

Hope this will help

Jay Ganesh

Posted in ASP.NET 3.5, ASP.NET Ajax, JQuery | Tagged: | 4 Comments »

Master-Detail Views with the ASP.NET Ajax Library by Dino Esposito

Posted by Ramani Sandeep on February 22, 2010

When you think of data-driven Web pages, most of the time what you really have in mind is a master-detail view of some cross-related data. Master-detail views are ideal for rendering one-to-many relationships, and such relationships are so common in the real world that a Web platform that doesn’t provide an effective set of tools for that functionality is inadequate.

ASP.NET Web Forms has always provided strong support for data binding and a powerful set of data-source and data-bound server controls. In Web Forms, server controls do a great job of rendering hierarchies of data using nearly any possible combination of grids, lists, and drop-down boxes and supporting multiple levels of nesting.

The drawback of the views you get out of Web Forms server controls is not the effectiveness of the rendering, but the static condition.

Users who navigate within a master-detail view typically switch among master records and drill down into the details of the records that are of interest. This interaction is the essence of a master-detail view.

In a classic Web Forms scenario, each drill-down operation may trigger a postback. Many postbacks—and subsequent page reloads— are not what makes users happy these days.

An alternative exists, but it’s not free of issues either. It basically consists of preloading any possible data the user might want to see. The data is then downloaded with the standard page and kept hidden using CSS styles. At the same time, any handler of user actions is rewritten to unveil hidden content rather than triggering a postback. As you can see, this is not an easy way to go.

The ASP.NET Ajax Library, in collaboration with jQuery, offers a much more powerful toolset and makes it possible to write smooth and effective master-detail views that post back asynchronously and only when strictly needed.

Read more

Jay Ganesh

Posted in ASP.NET 4.0, JQuery | Tagged: , | 2 Comments »

Consuming WCF / ASMX / REST service using JQuery By Sridhar Subramanian

Posted by Ramani Sandeep on February 22, 2010

In this article I will explain how to consume a WCF / ASMX service using jQuery.  The scope of the article is limited to creating &  consuming different kind of services using jQuery. I have segregated this article into 7 topics based on the service consumption.

  1. Calling ASMX Web service using jQuery
  2. Calling WCF service using jQuery and retrieving data in JSON Format
  3. Calling WCF service using jQuery and retrieving data in XML Format
  4. Calling WCF service using jQuery and retrieving data in JSON Format (pass multiple input parameters) & ( Get multiple objects as output using DataContract)
  5. Calling WCF service using jQuery[ Get Method] and retrieving data in JSON Format
  6. Calling REST based WCF service using jQuery
  7. Streaming an image through WCF and request it through HTTP GET verb..

If you have never heard about jQuery or WCF or JSON, please learn it before dwelling into this article. The scope  is limited to service creation and consumption.

Read more

Hope this will help

Jay Ganesh

Posted in JQuery, WCF, Web Services | Tagged: , , , | 3 Comments »

CheckBoxList validation using JQuery

Posted by Ramani Sandeep on February 10, 2010

Every ASP.NET developer needs validation on CheckBoxList that can be one of these two:

  1. Check for RequiredField
  2. Check for Maximum Selection Limit

Check for RequiredField

I will be using JQuery to interecept the click event of each single Checkbox inside the CheckBoxList and then update a hidden TextBox control which has a RequiredFieldValidator associated to it, when a CheckBox is clicked.

When all CheckBoxes were unselected, the hidden TextBox would have nothing in it which makes the RequiredFieldValidator throws a JavaScript message on Submit.

Listing – 1 : CheckBoxList

 <asp:CheckBoxList ID="cblBusinessType" runat="server" CssClass="checkbox" ValidationGroup="VGEdit">
 </asp:CheckBoxList>

 <asp:Label ID="Label12" runat="server" Text="Select up to 3 Business Types" CssClass="label_black"></asp:Label>
 <asp:TextBox ID="txtCheckbox" runat="server" ValidationGroup="testGroup" style='display: none;'/>

<asp:RequiredFieldValidator ID="valCheckboxList" Display="Dynamic"
           ErrorMessage="At least one business type must be selected"
           runat="server" ControlToValidate="txtCheckbox"
           ValidationGroup="VGEdit" EnableClientScript="true" CssClass="ErrorLabel_10"
           SetFocusOnError="true"/>

Listing – 2 : jQuery Script for RequiredFieldValidator

  <script type="text/javascript">
        $(function() {
            function checkBoxClicked() {
                //Get the total of selected CheckBoxes
                var n1 = $("#<%= cblBusinessType.ClientID %> input:checked").length;
                //Set the value of the txtCheckbox control
                $("input:#<%= txtCheckbox.ClientID %>").val(n1 == 0 ? "" : n1);
            }
            //intercept any check box click event inside the #list Div
            $("#<%= cblBusinessType.ClientID %> :checkbox").click(checkBoxClicked);

        });
    </script>

Check for Maximum Selection Limit

We also often need to check that user can select only n items from the checkboxlist. so for that I have anothe jQuery script that help the developer to restrict the user from selection after he reach the max limit.

Listing – 3 : jQuery Script for Maximum Selection Limit

 <script type="text/javascript" language="javascript">
         //Count the Total Selection in CheckBoxList - BusinessType
         $('#<%= cblBusinessType.ClientID %>').find('input:checkbox').click(function()
         {
              var totCount=0;

              jQuery('#<%= cblBusinessType.ClientID %>').find("input:checkbox").each(function() {

              if (jQuery(this).attr("checked"))
              {
                totCount++;
              }

            });
            if(totCount > 3)
            {
                alert("Select up to 3 Business Types only...");
                return false;
            }

            return true;

         });
 </script>

Here in this function I have counted each selected checkbox by using jQuery selector each time user check/uncheck the checkbox. once the count goes beyond the limit flag the error message to user to remind that you have crossed the limit.

Hope this will Help
Jay Ganesh

Shout it kick it on DotNetKicks.com

Posted in JQuery | Tagged: , , | 4 Comments »

Create an ASP.NET TextBox Watermark Effect using jQuery

Posted by Ramani Sandeep on February 1, 2010

This short article demonstrates how to create a watermark effect on your TextBox and display instructions to users, without taking up screen space.

Note that for demonstration purposes, I have included jQuery code in the same page. Ideally, these resources should be created in separate folders for maintainability. \

Read more

Shout it

Posted in JQuery | Tagged: , | Leave a Comment »

Cascading DropDownLists With ASP.NET and jQuery

Posted by Ramani Sandeep on January 25, 2010

Cascading drop down lists is a really nice feature for web developers. I thought it was time to write an article on how to do this using ASP.NET and jQuery. Well here’s one way of doing it. Before we get started, this example uses the latest version of jQuery which is 1.3.2. That can be downloaded from here.

Read full article here :

http://www.dotnetcurry.com/ShowArticle.aspx?ID=417&AspxAutoDetectCookieSupport=1

Hope this will help

Shout it

Posted in ASP.NET 3.5, JQuery | Tagged: , | 3 Comments »

Lazy Loading

Posted by Ramani Sandeep on December 11, 2009

Introduction

Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program’s operation if properly and appropriately used. The opposite of lazy loading is Eager Loading.

Article – 1: jQuery Tabs and Lazy Loading by Malcolm Sheridan

In this article I will connect to the Northwind database using LINQ to SQL, and display customer and product information in separate tabs. I’ll also show you one way of lazy loading these tabs so the data is retrieved only once, not each time a tab is selected.

Read more

Article – 2: Lazy Loading jQuery Tabs with ASP.NET by Mikesdotnetting

This article looks at efficient use of jQuery tabs when displaying data. Specifically, it covers how to lazy-load data, so that it is only accessed and displayed if the tab is clicked.

Lazy Loading is a well-known design pattern that is intended to prevent redundant processing within your application. In the case of tabbed data, there seems little point retrieving and binding data that appears in a tabbed area that no one looks at. So, this examples covers how to defer data access and display until the user wants it – which is defined by them clicking the relevant tab.

Read more

Article – 3: Eager Loading and Lazy Loading in ADO.NET Data Services by Gil Fink

The default behavior of a data service’s .NET client is not to load the entities’ associated objects. When we request an entity we will get it from the service but its associated objects will not load up at all.

Lets say that I have two entities in my program

  • a course
  • a department

The associations between the entities are that a department can have a lot of courses and a course belongs to one department.

When I load a department it’s list of courses will be empty. trying to iterate the list of courses will give nothing because the courses will not load until we tell them to be loaded explicitly.

This is done by the LoadProperty method of the data service context.

Read more

 

I have a great learning experience thru this.

Now its your turn to have it.

kick it on DotNetKicks.com
Shout it

Posted in ASP.NET, ASP.NET 3.5, ASP.NET Ajax, C# 3.0, JQuery, Linq | Tagged: , , , , , , , | Leave a Comment »

Hide/Change Sort expression link in gridview

Posted by Ramani Sandeep on November 27, 2009

Today I was reading www.asp.net forums for some Q/A  & I found one interesting Query regarding Gridview sorting. So I feel that let me share it with others also.

Query Posted by Kamran Shahid

I am using built in sorting in gridview. The links on the headers column shows like

javascript:__doPostBack(‘GridView1′,’Sort$au_fname’)

Is tehre any way I can change the display of that link like for example it may show # or au_fname only.

Solutions by Imran Baloch

With JQuery

<script language="javascript">  
$(function(){      
    $("a[href]").each(function(n){  
        if(this.href.indexOf("GridView1")>-1)  
        {  
            var a=this.href;  
            this.href="#";  
            $(this).click(function(event){  
                this.href=a;  
            });              
        }  
    });  
});  
</script>  

Without JQuery

<script language="javascript">  
 var tags = document.getElementsByTagName('a');  
 for (var i=0; i < tags.length; i++)  
 {  
      if(tags[i].href.indexOf("GridView1")>-1)   
      {  
            tags[i].custom1=tags[i].href;  
            tags[i].href="#";  
            tags[i].onclick=function(event){  
                alert(this.custom1);  
                thisthis.href=this.custom1;  
            }  
      }  
 }   
</script>  

Hope this will help !!!

Happy Programming

Posted in ASP.NET, ASP.NET 3.5, JavaScript, JQuery | Tagged: , , , | Leave a Comment »

Moving Values Between Select Boxes

Posted by Ramani Sandeep on November 2, 2009

These functions allowed you to do commonly-requested actions with select boxes.

For example, you can easily pass values between two select boxes. This makes a nice Windows-style interface for choosing components, adding and removing items from a list, etc. Options are re-ordered as they are added and removed from the lists.

Several other functions are included in the source that are not in the examples. This includes copying items in lists instead of moving them, copying/moving all items, and automatically selecting all items in a list.

read more

Other related articles 

Posted in JavaScript, JQuery | Tagged: , , | Leave a Comment »

Multiple File Upload using JQuery

Posted by Ramani Sandeep on October 28, 2009

Introduction

In this article I have explained how to upload multiple files using file upload control. I have used jQuery plugin for uploading multiple files.

I have also explained how to check for file type, file maximum size limit using jQuery & also using server side validation code.

Download the Following Files

Namespace used

using System.Security.Cryptography;
using System.Text;
using System.IO;

Step 1: Include the jQuery Files needed on the page.

Assuming you have downloaded these files, create a reference to these files in the <head> section of your page as shown below:

  <head id="Head1" runat="server">
        <title>Multiple File Upload using JQuery</title>
        <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
        <script src="Scripts/jquery.MultiFile.js" type="text/javascript">
        </script>
    </head>

Step 2: Add File Upload Control & Button on the Page.

 <asp:FileUpload ID="FileUpload1" runat="server" class="multi" accept="gif|jpeg|bmp|png|jpg"
        maxlength="5" />
    <br />
    <asp:Button ID="btnUpload" runat="server" Text="Upload All" OnClick="btnUpload_Click" />
    <br />
    <asp:Label ID="lblMsg" runat="server" Text="">\
    </asp:Label>

class=”multi” is used to specify that user can select multiple files.
maxlength property specify that user can upload maximum 5 files not more than that.
accept property used to restrict user to upload only certain type of file only.

Step 3: Double click on Upload Button & Write the code that is used to upload files.

 protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (ServerSideValidation() == true)
        {
            string SavePath, Msg = null;

            // Get the HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    SavePath = ConfigurationManager.AppSettings["PatientPhotoImages"].ToString()
                        + GetUniqueKey() + GetFileExtension(hpf.FileName);
                    hpf.SaveAs(Server.MapPath(SavePath));
                    //SavePath can be saved in DB.
                    Msg += GetFileName(hpf.FileName.ToString()) + " , ";
                }
            }
            lblMsg.Text = Msg + " Uploaded Successfully.";
        }
    }

Step 4: Write the private function which helps to Upload files.

This function helps to extract file extension from the fileName.

 private string GetFileExtension(string FileName)
    {
        char saperator = '.';
        string[] temp = FileName.Split(saperator);

        return "." + temp[1].ToString();
    }

OR

private string GetFileExtension(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.Extension;
    }

This function helps to get Unique Key, which is used to save files on server with different name that does not collied with each other.

 private string GetUniqueKey()
    {
        int maxSize = 8;
        char[] chars = new char[62];
        string a;

        a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

        chars = a.ToCharArray();

        int size = maxSize;
        byte[] data = new byte[1];

        RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();

        crypto.GetNonZeroBytes(data);
        size = maxSize;
        data = new byte[size];
        crypto.GetNonZeroBytes(data);
        StringBuilder result = new StringBuilder(size);

        foreach (byte b in data)
        {
            result.Append(chars[b % (chars.Length - 1)]);
        }

        return result.ToString();
    }

This function help to get Filename from the filepath.

 private string GetFileName(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.Name;
    }

Step 5: Add Server Side Validation Code

This is the function which is used to validate files that user wants to upload. If the client side validation does not work, this code will help us to identify the invalid files.

Validation rules like whether file type is correct or not, file size is valid or not.

If you do not want to validate the files on server side, you can ignore this code. But I prefer to use it.

 private bool ServerSideValidation()
    {
        string errorMsg = string.Empty, temp = null;
        bool errorFlag = true;

        // Get the HttpFileCollection
        HttpFileCollection hfc = Request.Files;
        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                temp = ValidateImage(hpf);
                if (temp != null)
                {
                    errorMsg += GetFileName(hpf.FileName.ToString()) + " has error : " + temp;
                    temp = null;
                }
            }
        }

        if (errorMsg != "")
        {
            lblMsg.Text = errorMsg;
            errorFlag = false;
        }
        return errorFlag;
    }

This function used to check file type & file size. If file is invalid than it will return error message.

 private string ValidateImage(HttpPostedFile myFile)
    {
        string msg = null;
        int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileUploadSizeLimit"].ToString());
        //Check Length of File is Valid or Not.
        if (myFile.ContentLength > FileMaxSize)
        {
            msg = msg + "File Size is Too Large.";
        }
        //Check File Type is Valid or Not.
        if (!IsValidFile(myFile.FileName))
        {
            msg = msg + "Invalid File Type.";
        }
        return msg;
    }

This function is used to check whether the file that user want to upload is valid file type or not.

private bool IsValidFile(string filePath)
    {
        bool isValid = false;

        string[] fileExtensions = { ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };

        for (int i = 0; i < fileExtensions.Length; i++)
        {
            if (filePath.ToUpper().Contains(fileExtensions[i]))
            {
                isValid = true; break;
            }
        }
        return isValid;
    }

Conclusion:

This code is complete solution that helps to upload multiple file using File Upload with jQuery plugin. I was always in a need of such code in my route work so I decided to write the code that helps others also.

Hope this will help !!!
Jay Ganesh

kick it on DotNetKicks.com Shout it

Posted in ASP.NET, JQuery | Tagged: , , , , | 43 Comments »

 
Follow

Get every new post delivered to your Inbox.

Join 317 other followers