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

Monday, June 9, 2014

Get the return value from ASP.NET Code behind function to the client using JQuery

Using Ajax POST method you can call ASP.NET Server side C# function from the client side. Here the GetSquareOfNumber function is called from client side and return the calculated value from the server when we click the Button2. The c# function should be static, decorated using [WebMethod] attribute and the parameter variable should be same as one we used in the ajax call "param". The returned value will be retrieved in the ajax success function. Use the Breakpoint to check the server code getting called or not.
Script in ASPX page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            $("#Button2").click(function ()
            {
                var num = $('#TextBox1').val();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetSquareOfNumber", // Your page and function name
                    data: '{param: "' + num + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data)
                    {
                        if (data.d != null)
                        {
                            alert(data.d);
                        }
                    },
                    failure: function (response)
                    {
                        console.log(response.d);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <input id="Button2" type="button" value="button" />
        </div>
    </form>
</body>
</html>

Namespace:

using System.Web.Services;

Code behind C#:

[WebMethod]
public static int GetSquareOfNumber(int param)
{
 return param * param;
}

Call and pass parameter to ASP.NET Code behind function from the client side using JQuery

Using Ajax POST method you can call ASP.NET Server side C# function from the client side with parameter also. Here the SendTheID function is called from client side and the TextBox1 value will be passed as a parameter when we click the Button2. The c# function should be static, decorated using [WebMethod] attribute and the parameter variable should be same as one we used in the ajax call "param". Use the Breakpoint to check the server code getting called or not.
Script in ASPX page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            $("#Button2").click(function ()
            {
                var num = $('#TextBox1').val();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/SendTheID", // Your page and function name
                    data: '{param: "' + num + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data)
                    {
                        //will return null
                    },
                    failure: function (response)
                    {
                        console.log(response.d);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <input id="Button2" type="button" value="button" />
        </div>
    </form>
</body>
</html>


Namespace:

using System.Web.Services;


Code behind C#:

[WebMethod]
public static void SendTheID(int param)
{
 int returnId = param;
//Write whatever you neeed..
}

Call ASP.NET Code behind function without parameter from the client side using JQuery

Using Ajax POST method you can call ASP.NET Server side C# function from the client side. Here the RunMe function is called from client side when we click the Button1. The c# function should be static and decorated using [WebMethod] attribute. Use the Breakpoint to check the server code getting called or not. Script in ASPX page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            $("#Button1").click(function ()
            {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/RunMe", // Your page and function name
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (res)
                    {
   //will return null
                        console.log(res);
                    },
                    failure: function (response)
                    {
                        console.log(response.d);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input id="Button1" type="button" value="button" />
        </div>
    </form>
</body>
</html>

Namespace:

using System.Web.Services;

Code behind C#:

[WebMethod]
public static void RunMe()
{
//Write whatever you neeed..
}

Monday, January 27, 2014

How to Set the ASP.NET Server Control Textbox value using JavaScript or Jquery

We can not access the server control by directly using it's id. You need to append and prepend the <%= and %> and also the ClientID. Because when rendering in browser the server control id will be change. If you are using JQuery to set the textbox value means you need to use # symbol. Check out the sample code clearly.
To get the server control value check my another post Click Here
HTML Code:
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>

JavaScript Code:
document.getElementById("<%= textbox1.ClientID %>").value = "values to set using JavaScript";

JQuery Code:
$("#<%= textbox1.ClientID %>").val("values to set using JQuery");

How to Get the ASP.NET Server Control Textbox value using JavaScript or Jquery

We can not access the server control value by directly using it's id. You need to append and prepend the <%= and %> and also the ClientID. Because when rendering in browser the server control id will be change. If you are using JQuery to get the textbox value means you need to use # symbol. Check out the sample code clearly.
To Set a value to server control check my another post Click Here
HTML Code:
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>

JavaScript Code:
var val1= document.getElementById("<%= textbox1.ClientID %>").value;

JQuery Code:
var val2= $("#<%= textbox1.ClientID %>").val();

Select only one checkbox at a time from the list of checkboxes using JQuery

Here i have created three checkbox named 1,2,3. When we click a checkbox, the name property of the current checkbox is retrived and checked using JQuery is() function and all other checkbox are unchecked using JQuery not() function.
HTML Code:
<input type="checkbox" name="fruits">1</input>
<input type="checkbox" name="fruits">2</input>
<input type="checkbox" name="fruits">3</input>

JQuery Code:
$(':checkbox').on('change',function(){
 var thiscb = $(this);
 var name = thiscb.prop('name');
 if(thiscb.is(':checked'))
 {
     $(':checkbox[name="'  + name + '"]').not($(this)).prop('checked',false);  
  }
});

Demo:

Click Here for Demo

Monday, January 20, 2014

Catch Asynchronous postback from Updatepanel in ASP.NET to Show / Hide loading image

In some situation we need to display loading image when the Asynchronous post back in AP.NET Updatepanel. For that we need to catch the Asynchronous postback event. The below code will catch the postback and get the corresponding id of the control that makes the postback. So using the controlId you need to find the Updatepanel from which the postback occurred. So that we can show and hide the loading images in the specific Updatepanel. To find the Updatepanel here i used JQuery's closest function. Check the code.
Client Script:

<script type="text/javascript">
        $(document).ready(function() {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            if (prm != null) {
                prm.add_beginRequest(function(sender, e) {
                    var controlId = sender._postBackSettings.sourceElement.id;
                    var closestUpdatePanel= $('#' + controlId).closest(".UpdatepanelClass")
                });
            }
            prm.add_endRequest(function(sender, e) {
                var controlId = sender._postBackSettings.sourceElement.id;
                var closestUpdatePanel = $('#' + controlId).closest(".UpdatepanelClass")  
            });
        });
</script>

Saturday, March 23, 2013

Create a Tab control using JQuery in ASP.NET

By using the below code we can make a simple JQuery tab control. In this example i am going to create two tab. When we click a tab a table will be hide and another table will be visible.
  • Befor start coding download and add latest JQuery library and refer it in code like below inside head section.
<script src='js/common/jquery-1.9.1.js' ></script>
  •  Then add the below JQuery code inside head section in ASP.NET HTML design page

<script type="text/javascript">
    $(document).ready(function () {
        $(".tabLink").each(function () {
            $(this).click(function () {
                tabeId = $(this).attr('id');
                $(".tabLink").removeClass("activeLink");
                $(this).addClass("activeLink");
                $(".tabcontent").addClass("hide");
                $("#" + tabeId + "-1").removeClass("hide")
                return false;
            });
        });
    });
 </script>
  • Then add the below code in body section. This is actually a tab design.
<table cellpadding="0" cellspacing="0">
    <tr>
        <td class="contact_tab_box">
        <a href="javascript:;" class="tabLink activeLink" id="tab1">Tab1</a>
        <a href="javascript:;" class="tabLink " id="cont-2">Tab2</a>
        </td>
    </tr>
</table>
  • Now we have to design two tables to work with the tab when we click it
<table width="100%" class="tabcontent" id="t1">
    <tr>
        <td>
        DO YOUR DESIGN HERE
        </td>
    </tr>
</table>

<table width="100%" class="tabcontent hide" id="t2"> <tr> <td> DO YOUR DESIGN HERE </td> </tr> </table>
  • We need the below CSS for better design
.contact_tab_bar_left {
    background: #F2F2F2;
}
.contact_tab_bar_right {
    background: #F2F2F2;     border-radius:0px 6px 6px 0px; }
.contact_tab_box {     background: #EEEEEE; }
.contact_tab_box a {     font-family:Arial;     font-size:14px;     border:1px solid #797979;     color:#000;
    padding: 7px 30px;     text-decoration:none;     background-color: #eee;     border-radius: 6px 6px 0px 0px;     -moz-border-radius: 6px 6px 0px 0px;     -webkit-border-radius: 6px 6px 0px 0px; }
.contact_tab_box a.activeLink {     font-family:Arial;     font-size:14px;     font-weight: bold;     background-color: #3F3F3F;     color:#FFFFFF;     border-bottom: 0;     padding: 7px 30px;     border-radius: 6px 6px 0px 0px;     -moz-border-radius: 6px 6px 0px 0px;     -webkit-border-radius: 6px 6px 0px 0px; }
.contact_tab_content {     border: 1px solid #797979;     -moz-border-radius: 6px;     -webkit-border-radius: 6px;     border-radius: 6px; } .hide { display: none;}