Updating controls via JQuery from inside an UpdatePanel

Recently we encountered an issue when we were trying (unsuccessfully) to update a link outside an Ajax UpdatePanel using jQuery.
We wrote the change events and we noticed that they only fired once and no more. Clicking on the tickbox proved to be futile. Not even 317 clicks seemed to work.
original

After a bit of research, we found out that the Update Panels only subscribe to the page load event once and afterwards they drop the events, unless you rebind them once more.
To rebind them, you need to call the PageRequestManager and connect to the endRequest method.

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {…});

$('#ctl00_ContentPlaceHolder1_chkLinkedSuppliers').on('change', function () {
        if ($('#ctl00_ContentPlaceHolder1_lnkAuditReport2').length > 0)
        {
            var href = $('#ctl00_ContentPlaceHolder1_lnkAuditReport2').attr("href");
            ///Reports/AuditReport2.aspx?ID=21074&ShowAll=0&ShowAllSystems=0&ShowAllCompanies=0&ShowAllLinked=1
            href = href.replace("&ShowAllLinked=1","").replace("&ShowAllLinked=0","");
            if($(this).is(":checked")) {
                href = href + "&ShowAllLinked=1";
            }else{
                href = href + "&ShowAllLinked=0";
            }

            $('#ctl00_ContentPlaceHolder1_lnkAuditReport2').attr("href", href);
        }

    });

    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_endRequest(function () {
        // re-bind your jQuery events here

        $('#ctl00_ContentPlaceHolder1_chkLinkedSuppliers').on('change', function () {
            if ($('#ctl00_ContentPlaceHolder1_lnkAuditReport2').length > 0) {
                var href = $('#ctl00_ContentPlaceHolder1_lnkAuditReport2').attr("href");
                ///Reports/AuditReport2.aspx?ID=21074&ShowAll=0&ShowAllSystems=0&ShowAllCompanies=0&ShowAllLinked=1
                href = href.replace("&ShowAllLinked=1", "").replace("&ShowAllLinked=0", "");
                if ($(this).is(":checked")) {
                    href = href + "&ShowAllLinked=1";
                } else {
                    href = href + "&ShowAllLinked=0";
                }

                $('#ctl00_ContentPlaceHolder1_lnkAuditReport2').attr("href", href);
            }

        });

It worked like a charm!

"text/javascript">
    function BindControlEvents() {
        //jQuery is wrapped in BindEvents function so it can be re-bound after each callback.
        //Your code would replace the following line:
            $('#').limit('100', '#charsLeft_Instructions');
    }

    //Initial bind
    $(document).ready(function () {
        BindControlEvents();
    });

    //Re-bind for callbacks
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_endRequest(function() {
        BindControlEvents();
    });

Advertisements

How to perform a file upload in an Update Panel

We know that we can upload file to server using File upload control. However, if we use file upload control inside update panel, then it doesn’t works. The reason for this is that file upload control doesn’t work with asynchronous postback. In this article, we would be working on making file upload control work with update panel and update progress.

This sample code uploads an mp3 file (with extension validation) to the server and automatically sets the expiry date one month from today. The Upload button causes a page postback.

The “extend” button will add one month to today and generate a new date output. This one is called async.

 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                
class="checkbox"> runat="server" ID="chkHasAudio" AutoPostBack="true" OnCheckedChanged="chkHasAudio_CheckedChanged" Text="Has Audio File?" />
<asp:Panel runat="server" ID="pnlUploadStuff">
class="col-md-4 col-sm-4"> Upload new file:
class="col-md-5 col-sm-5"> ID="fileUploadImage" runat="server">
class="col-md-3 col-sm-3 "> ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" CssClass="btn btn-default pull-right" CausesValidation="false" />
class="clearfix">
<asp:Label runat="server" ID="lblErrorUpload" CssClass="alert alert-danger" />
class="clearfix">
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1"> <ProgressTemplate> Please wait while the audio is getting uploaded.... </ProgressTemplate> </asp:UpdateProgress> <br /> <i class="fa fa-download"></i> <asp:HyperLink runat="server" ID="hyperFile" Target="_blank" /> <br /> <br /> <i class="fa fa-times"></i> File is available until: <asp:Label runat="server" ID="lblAvailableUntil" CssClass="label label-cyan" /> <asp:Button runat="server" ID="btnExtend" Text="Extend" OnClick="btnExtend_Click" CssClass="btn btn-default" CausesValidation="false" /> </asp:Panel> </ContentTemplate> <Triggers> <asp:PostBackTrigger ControlID="btnUpload" /> <asp:AsyncPostBackTrigger ControlID="btnExtend" /> </Triggers> </asp:UpdatePanel>

Code behind (in c#)

  protected void chkHasAudio_CheckedChanged(object sender, EventArgs e)
        {
            pnlUploadStuff.Visible = chkHasAudio.Checked;
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (fileUploadImage.HasFile)
            {

                string fileName = fileUploadImage.FileName;
                if (System.IO.Path.GetExtension(fileUploadImage.PostedFile.FileName).ToLower().Replace(".", "") != "mp3")
                {
                    lblErrorUpload.Text = "Please select an MP3 file!";
                    lblErrorUpload.Visible = true;
                }
                else
                {

                    try
                    {
                        fileUploadImage.SaveAs("~/Uploads/" + fileName);
                        hyperFile.Text = fileName;
                        hyperFile.NavigateUrl = "~/Uploads/" + fileName;
                        lblAvailableUntil.Text = DateTime.Now.AddMonths(1).ToShortDateString();
                    }
                    catch (Exception ex)
                    {
                        lblErrorUpload.Text = "Could not save file! " + ex.Message;
                        lblErrorUpload.Visible = true;
                    }
                }
            }
            else {
                lblErrorUpload.Text = "Please select a file!";
                lblErrorUpload.Visible = true;
            }
        }

        protected void btnExtend_Click(object sender, EventArgs e)
        {
            lblAvailableUntil.Text = DateTime.Now.AddMonths(1).ToShortDateString();
        }

Call SOAP-XML Web Services With jQuery Ajax

if you would like to call a webservice which returns an XML format, why not have a read at this article:
http://openlandscape.net/2009/09/25/call-soap-xm-web-services-with-jquery-ajax/

function CallClientIDWebService() {
            var URL = "https://test.NJ.samole.com/apps/Service/SampleService/NRK/Employees";
            jQuery.ajax({
                type: "POST",
                url: URL,
                dataType: "xml",
                contentType: "application/xml; charset=utf-8",
                success: function (data) {
                    //edata = $(data).find("string").text();
                    debugger;
                    alert(data);
                }
            })
        }

Customize ajax loading image in jQuery mobile

In jQuery mobile v 1.0, to change defalt styling of ajax loading and search bar icon customize following default css.

Customize ajax loading image using css
.ui-loader .ui-icon {
background-color: transparent;
}

.ui-loader-default {
opacity: 1;
}

.ui-icon-loading {
background: url(YOUR URL) no-repeat;
}

Customize search bar icon using css
.ui-icon-search, .ui-icon-searchfield:after {
background-position: 0px 100%;
}

.ui-icon, .ui-icon-searchfield:after {
background: url(YOUR URL) no-repeat;
border-radius: 9px 9px 9px 9px;
background-size: 16px 16px;
}

.ui-icon-searchfield:after
{
opacity:1;
}

 

How to create a JSON POST request from a GET method

Let’s say you find a security hole in your system from old developers – leaving one of your webservices exposed:

http://mywebservice/MyService.asmx/SendEmail?Username=1234&Password=1224!&EmailFrom=no-reply@carra-lucia-ltd.co.uk&EmailTo=carra_lucia@hotmail.com&Subject=MySubject&Message=Dear%20Administrator,test%20mail%20here

Now how would you transform this into a POST string with JSON?


  var myURL = "http://mywebservice/MyService.asmx/SendEmail";
        var dataToUse = $.parseJSON('{"Username": "1234","Password":"1224!","EmailFrom":"no-reply@carra-lucia-ltd.co.uk","EmailTo":"carra_lucia@hotmail.com","Subject":"MySubject","Message":"' + msg + '"}');
        $.ajax({
            type: "POST",
            url: myURL,
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp",
            data: dataToUse,
            crossDomain: true,
            success: function (response) {
                //email was sent
                alert("Email has been sent successfully!");
            },
            error: function (jqXHR, error, errorThrown) {
                if (jqXHR.status && jqXHR.status == 400) {
                    alert(jqXHR.responseText);
                } else {
                    alert("Something went wrong. We could not send your email.");
                }
            }
        });

MySubject

Using jQuery ajax to call asmx webservice methods

One imprtant distinction is what I mean by a JSON object and JSON format.  A JSON object is an object that can be used by javascript

var o = {data: 'value'};
alert (o.data); // this works as o is an object

JSON format is simply a literal string that can be turned into a JSON object if we parse it

var f = "{data: 'value'}";
alert (f.data); // this won't work as f is just a string and string doesn't have a data property

The following code calls a webservice that has three different SayHello functions.

[WebMethod]
public string SayHello(string firstName, string lastName)
{
    return "Hello " + firstName + " " + lastName;
}

[WebMethod]
public string SayHelloJson(string firstName, string lastName)
{
    var data = new { Greeting = "Hello", Name = firstName + " " + lastName };

    // We are using an anonymous object above, but we could use a typed one too (SayHello class is defined below)
    // SayHello data = new SayHello { Greeting = "Hello", Name = firstName + " " + lastName };

    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

    return js.Serialize(data);
}

[WebMethod]
public SayHello SayHelloObject(string firstName, string lastName)
{
    SayHello o = new SayHello();
    o.Greeting = "Hello";
    o.Name = firstName + " " + lastName;

    return o;
}

“SayHello” returns a string

“SayHelloJson” returns a string that is an object in JSON format

“SayHelloObject” returns an object.  The SayHello class is here

public class SayHello
{
    public string Greeting { get; set; }
    public string Name { get; set; }
}

I have added the comments inline on the code, but the examples cover calling all three types of webservice method, and they also cover getting simple text back and getting JSON objects back, and also sending parameters in form encoded formats and also JSON formats.

Enjoy

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="WebTest.ajax.test" %>

<!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>
        http://../Scripts/jquery-1.4.1.js
</head>
<body>
    <form id="form1" runat="server">
    

Example A

Example B

Example C

Example D

Example E
/* SayHello returns a string SayHelloJson returns a string that is an object in JSON format SayHelloObject returns an object [WebMethod] public string SayHello(string firstName, string lastName) { return "Hello " + firstName + " " + lastName; } [WebMethod] public string SayHelloJson(string firstName, string lastName) { var data = new { Greeting = "Hello", Name = firstName + " " + lastName }; // We are using an anonymous object above, but we could use a typed one too (SayHello class is defined below) // SayHello data = new SayHello { Greeting = "Hello", Name = firstName + " " + lastName }; System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); return js.Serialize(data); } [WebMethod] public SayHello SayHelloObject(string firstName, string lastName) { SayHello o = new SayHello(); o.Greeting = "Hello"; o.Name = firstName + " " + lastName; return o; } public class SayHello { public string Greeting { get; set; } public string Name { get; set; } } */ $(document).ready(function () { // SayHello returns a string we want to display. Examples A, B and C show how you get the data in native // format (xml wrapped) as well as in JSON format. Also how to send the parameters in form-encoded format, // JSON format and also JSON objects. To get JSON back you need to send the params in JSON format. // Example A - call a function that returns a string. // Params are sent as form-encoded, data that comes back is text $.ajax({ type: "POST", url: "MyWebService.asmx/SayHello", data: "firstName=Aidy&lastName=F", // the data in form-encoded format, ie as it would appear on a querystring //contentType: "application/x-www-form-urlencoded; charset=UTF-8", // if you are using form encoding, this is default so you don't need to supply it dataType: "text", // the data type we want back, so text. The data will come wrapped in xml success: function (data) { $("#searchresultsA").html(data); // show the string that was returned, this will be the data inside the xml wrapper } }); // Example B - call a function that returns a string. // Params are sent in JSON format, data that comes back is JSON $.ajax({ type: "POST", url: "MyWebService.asmx/SayHello", data: "{firstName:'Aidy', lastName:'F'}", // the data in JSON format. Note it is *not* a JSON object, is is a literal string in JSON format contentType: "application/json; charset=utf-8", // we are sending in JSON format so we need to specify this dataType: "json", // the data type we want back. The data will come back in JSON format success: function (data) { $("#searchresultsB").html(data.d); // it's a quirk, but the JSON data comes back in a property called "d"; {"d":"Hello Aidy F"} } }); // Example C - call a function that returns a string. // Params are sent as a JSON object, data that comes back is text $.ajax({ type: "POST", url: "MyWebService.asmx/SayHello", data: { firstName: 'Aidy', lastName: 'F' }, // here we are specifing the data as a JSON object, not a string in JSON format // this will be converted into a form encoded format by jQuery // even though data is a JSON object, jQuery will convert it to "firstName=Aidy&lastName=F" so it *is* form encoded contentType: "application/x-www-form-urlencoded; charset=UTF-8", dataType: "text", // the data type we want back, so text. The data will come wrapped in xml success: function (data) { $("#searchresultsC").html(data); // show the data inside the xml wrapper } }); // SayHelloJson returns a .net object that has been converted into JSON format. So the method still return a // string, but that string is an object in JSON format. It is basically an object within an object. We still // get the "d" property back as in Example B, but "d" is an object represented in JSON format itself. // Example D - call a function that returns a string that is an object in JSON format. // Params are sent in JSON format, data that comes back is a string that represents an object in JSON format $.ajax({ type: "POST", url: "MyWebService.asmx/SayHelloJson", data: "{ firstName: 'Aidy', lastName: 'F' }", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var myData = JSON.parse(data.d); // data.d is a JSON formatted string, to turn it into a JSON object // we use JSON.parse // now that myData is a JSON object we can access its properties like normal $("#searchresultsD").html(myData.Greeting + " " + myData.Name); } }); // SayHelloObject returns a typed .net object. The difference between this and Example D is that in Example D // the "d" property is an object in JSON format so we need to parse it to make it a JSON object. Here the // "d" property is already an actual JSON object so no need to parse it. // Example E - call a function that returns an object. .net will serialise the object as JSON for us. // Params are sent in JSON format, data that comes back is a JSON object $.ajax({ type: "POST", url: "MyWebService.asmx/SayHelloObject", data: "{ firstName: 'Aidy', lastName: 'F' }", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var myData = data.d; // data.d is a JSON object that represents out SayHello class. // As it is already a JSON object we can just start using it $("#searchresultsE").html(myData.Greeting + " " + myData.Name); } }); }); </form> </body> </html>