Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Wednesday, September 23, 2009

Binding the multiple drop down boxes in GridView using JQuery in ASP.NET

Here is the code for binding the multiple drop down boxes in GridView using JQuery in ASP.NET


ASPX and JQuery code:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TimeSheetGrid.ascx.cs" Inherits="TimesheetApp.UserControls.TimeSheetGrid" %>
<script src="../Script/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
    $("select[id$='cboWorkPackage']").each(function()
    {
        getWorkPackages($(this));
    }
    );
   
    $("select[id$='cboModule']").each(function()
    {
        getModules($(this));
    }
    );
}
);

function getWorkPackages(t) {
  $.ajax({
    type: "POST",
    url: "/WebMethods/GridValuesService.asmx",
    data: "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><GetWorkPackages xmlns='http://tempuri.org/'><ProjectId>" + $("span[id$='lblProjectValue']").html() + "</ProjectId></GetWorkPackages></soap:Body></soap:Envelope>",
    contentType: "text/xml; charset=\"utf-8\"",
    dataType: "xml",
    success: function(response)
    {
     
    },
    complete: function (result,status)
    {
    $(result.responseXML).find("WorkPackage").each(function()
        {
       
           
            var val = $(this).find("WPId").text();
            var text = $(this).find("WPCode").text();
            var myOptions = {
                                val1 : val,
                                val2 : text
                            };
             t.append
                (
                $('<option></option>').html(text).val(val)
                );              
               
        }
    );
    },
    error: function (result,status)
    {
    alert(status);
    }
  });
}


function getModules(t) {
  $.ajax({
    type: "POST",
    url: "/WebMethods/GridValuesService.asmx",
    data: "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><GetModules xmlns='http://tempuri.org/'><WorkPackageId>" + 1 + "</WorkPackageId></GetModules></soap:Body></soap:Envelope>",
    contentType: "text/xml; charset=\"utf-8\"",
    dataType: "xml",
    success: function(response)
    {
     
    },
    complete: function (result,status)
    {
    $(result.responseXML).find("Module").each(function()
        {
       
           
            var val = $(this).find("ModuleId").text();
            var text = $(this).find("ModuleCode").text();
            var myOptions = {
                                val1 : val,
                                val2 : text
                            };
             t.append
                (
                $('<option></option>').html(text).val(val)
                );              
               
        }
    );
    },
    error: function (result,status)
    {
    alert(status);
    }
  });
}
</script>
<asp:GridView ID="grdTimeSheetView" runat="server" AutoGenerateColumns="false" EnableViewState="true">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:Label ID="lblProject" runat="server" Text="Project"></asp:Label>
            </HeaderTemplate>
            <ItemTemplate>
               <asp:Label ID="lblProjectValue" runat ="server" Text ='<%# Eval("ProjectId") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:Label ID="lblWorkPkg" runat="server" Text ="Work Package"></asp:Label>
            </HeaderTemplate>
            <ItemTemplate>
                <asp:DropDownList ID="cboWorkPackage" runat ="server" EnableViewState ="true"></asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
        <HeaderTemplate>
        <asp:Label ID="lblModule" runat="server" Text ="Module"></asp:Label>
        </HeaderTemplate>
            <ItemTemplate>
                <asp:DropDownList ID="cboModule" runat ="server" EnableViewState ="true"></asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
 


Web Service and Web Methods


/// <summary>
    /// Summary description for GridValuesService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class GridValuesService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public List<WorkPackage> GetWorkPackages(long ProjectId)
        {
            WorkPackageDAL wp = new WorkPackageDAL();
            return wp.GetWorkPackages(ProjectId);
        }
        [WebMethod]
        public List<Module> GetModules(long WorkPackageId)
        {
            ModuleDAL module = new ModuleDAL();
            return module.GetModules(WorkPackageId);
        }

    }





Friday, September 18, 2009

Issue with "$(document).ready(function() {...}" in JQuery

Today one of my friend faced a peculiar issue with JQuery. He told me, JQuery is working fine for ASP.NET controls if he add the JQuery code inline. But it is not working, if he move the code to an .js file and use it in the page.
Then we thought something wrong with the intelligent selector in JQuery. But the syntax of the intelligent looked perfect and no issues were there.
$("input[id$='txtName']").val("Text Added using jQuery");

Then I asked him, are you sure you have only one "$(document).ready(function() {...}" in the ASP.NET page. That ring a bell and when he checked, it was present in ASP.NET page and in .js file. Once he remvoed the "$(document).ready(function() {...}" from one place, Bingo!!! it started working.

Hence, an ASP.NET page can contain only one "$(document).ready(function() {...}". We need to be sure that, in the referenced .js files and in the inline javascript code it should not be present more than once.

Show/Hide Datagrid columns using JQuery


Recently one of our customer came with a special requirement of letting the users to show/hide the columns in a grid as he wish. The customer was little hesitant to ask for this requirement. (he was thinking, it will be difficult to achieve). But we gave him confidence by achieving this by using JQuery. This is how we achieved this functionality


Grid code:

<asp:GridView ID="grdView" runat="server" AutoGenerateColumns="false" OnRowDeleting="grdView_RowDeleting"
    EnableViewState="true">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <div id="ColAH" >
                    <asp:ImageButton ID="ImageButtonDelete2" runat="server" ImageUrl="~/_assets/img/delete.png"
                        CssClass="deleteButton" />
                </div>
            </HeaderTemplate>
            <ItemTemplate>
                <div id="ColA" class="columnA">
                    <asp:Label ID="l1" runat="server" Text='<%# Eval("ColA") %>'></asp:Label>
                </div>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <HeaderTemplate>
                <div id="ColBH" >
                    <asp:ImageButton ID="ImageButtonDelete1" runat="server" ImageUrl="~/_assets/img/delete.png"
                        CssClass="deleteButton" />
                </div>
            </HeaderTemplate>
            <ItemTemplate>
                <div id="ColB" class="columnB">
                    <asp:Label ID="l2" runat="server" Text='<%# Eval("ColB") %>'></asp:Label>
                </div>
            </ItemTemplate>
        </asp:TemplateField>
       
    </Columns>
</asp:GridView>


Javascript code:

    $(document).ready(function() {
       
        
        $('#ColAH').each(
            function(e)
            {
            $(this).find(".deleteButton").click(
                function (e)
                {
                e.preventDefault();
                var res = getDivs('columnA');
                    for(var i=0; i
                    {
                        var state = res[i].style.display;
                        if (state == 'block' || state == '')
                        {
                            res[i].style.display = 'none';
                        }
                        else
                        {
                            res[i].style.display = 'block';
                        }
                        alert(res[i].style.display);
                    }
                }
               
            );
            }
        );
       
         $('#ColBH').each(
            function(e)
            {
            $(this).find(".deleteButton").click(
                function (e)
                {
                e.preventDefault();
                var res = getDivs('columnB');
                    for(var i=0; i
                    {
                        var state = res[i].style.display;
                        if (state == 'block' || state == '')
                        {
                            res[i].style.display = 'none';
                        }
                        else
                        {
                            res[i].style.display = 'block';
                        }
                        alert(res[i].style.display);
                    }
                }
               
            );
            }
        );
       
    });

    function deleteRow(args) {
        $(args).click();
        return false;
    }
   
    function getDivs(cName)
    {
    var ar = document.getElementsByTagName("div");
    var divArray = new Array();
   for(var i=0; i
     if(ar[i].className == cName ){
        divArray.length++;
        divArray[divArray.length -1] = ar[i];
     }
  }
  return divArray;
}
  
function hideColumn(id)
{
var state = document.getElementById(id).style.display;
if (state == 'block' || state == '') {
     document.getElementById(id).style.display = 'none';
} else {
       document.getElementById(id).style.display = 'block';
   }
}
    function confirm(message, callback) {
        $('#confirm').modal({
            close:false,
            overlayId:'confirmModalOverlay',
            containerId:'confirmModalContainer',
            onShow: function (dialog) {
                dialog.data.find('.message').append(message);

                // if the user clicks "yes"
                dialog.data.find('.yes').click(function () {
                    // call the callback
                    if ($.isFunction(callback)) {
                        callback.apply();
                    }
                    // close the dialog
                    $.modal.close();
                });
            }
        });
     }
                           
 And don't forget to include the Jquery.


Kudo to JQuery!!!!! JQuery is a proof for "Impossible is Nothing"!!!!