Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery + AJAX + ASP.Net + WebForms

Tags:

jquery

c#

ajax

I have some JQuery AJAX POSTing data to my backend C# WebForm. It POSTs to a static string WebForm method which returns a value, the JQuery uses that value to change an image url in the html. All is fine and dandy.

However, I would like to expand the functionality of the existing code (though I'm not shut out to rewriting it altogether) to allow me to manipulate the front end ASP controls from the C# backend, which I can not do due to the said static string method acting as my WebForm.

Does anyone have any ideas to help my predicament?

Backend

    [System.Web.Services.WebMethod]
    public static string ImageLoad(string address)
    {
        //if fail
        return "/Unavailable.bmp";

        //if succeed
        return "myimage.jpg";
        //third option
        else
        return "myotherimage.jpg";
    }

JQuery/AJAX

function scriptImageLoad() {
   var address = $("#txtAddress").val();
       $.ajax({
           type: "POST",
           url: "myPage.aspx/ImageLoad",
           data: "{'address':'" + address.toString() + "'}",
           contentType: "application/json; charset=utf-8",
           dataType: "text",
           success: function (output) {
                $('#imgImage').attr('src', output);
           }
       });
   }
});
like image 369
Kevin Avatar asked Aug 24 '26 11:08

Kevin


2 Answers

Use a WebService. This will allow you to call the service with jQuery anywhere in your website.

function scriptImageLoad() {
   var address = $("#txtAddress").val();
       $.ajax({
           type: "POST",
           url: "MyService.asmx/ImageLoad",
           data: "{'address':'" + address.toString() + "'}",
           contentType: "application/json; charset=utf-8",
           dataType: "text",
           success: function (output) {
                $('#imgImage').attr('src', output);
           }
       });
   }
});

[WebService, ScriptService]
public class MyService : WebService
{
    [ScriptMethod]
    public static string ImageLoad(string address)
    {
        //if fail
        return "/Unavailable.bmp";

        //if succeed
        return "myimage.jpg";
        //third option
        else
        return "myotherimage.jpg";
    }
}
like image 191
jrummell Avatar answered Aug 27 '26 01:08

jrummell


A postback of some sort is required to process server controls.

Update panels are your only real choice for working with asp.net controls in this scenario.

But I would suggest finding another approach - update panels are evil and will give you warts. the bad kind.

like image 45
Sky Sanders Avatar answered Aug 27 '26 02:08

Sky Sanders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!