0

I'm new to integrating JavaScript into a web site, but I'm going to need it often in my web site.

Here is an example: Assuming I have the function:

showAlert()

Say I have:

<div id="some_div">

</div>

Could someone provide me some kind of example that would do this: If I have a button and the user clicks it, this should raise an event in the backend and call some method in my C# file. Then my C# file should be able to call some other javascript method of the front end which would call showAlert() and display the alert in the div.

This is what I can't seem to find any information on.

The basic idea of passing information to and from the server. Any help with this would be really appreciated.

Thanks

jmasterx
  • 52,639
  • 96
  • 311
  • 557
  • 1
    What you probably want to start reading about is Ajax. Otherwise, this is way too broad to properly answer here. – Andrew Barber Jan 31 '13 at 14:42
  • Isn't a callback function sufficient? Like `jQuery.ajax` with its success callback. – Lim H. Jan 31 '13 at 14:42
  • Could you point me to a link or tutorial? – jmasterx Jan 31 '13 at 14:45
  • 1
    Note also that the backend will never be able to "call a javascript method on the front end", all you can do is perform ajax calls from the front end to the backend and deal with whatever is returned. – Peter Herdenborg Jan 31 '13 at 14:47
  • @PeterHerdenborg Excellent point and this is critical to understanding how front end async technologies work. You have to alienate the Webforms mentality and get used to calling and handling your calls in the client. – David L Jan 31 '13 at 14:48

1 Answers1

3

Your best bet is to use a framework like jquery, then bind to the button, call the service, and handle the response. The below is a quick example of this.

$(document).ready(function()
    $('#Button1').bind('click', function () { 
        // This grabs the page you are in so that you can call it correctly
        var pagePath = window.location.pathname;  
        var testId = $("#some_div").val();
        var url = pagePath + "/TestService";          
        $.post(url, { id: testId },
            function (data) {
                showAlert(data);
            }
        });
    };
});

First, you need to make sure the document is ready at some point. Bind allows the the button to be bound when the document loads. Then, by clicking it, you execute the anonymous function that grabs the testId, calls your service, and handles the data response in a success callback.

Hope that gets you started in the right direction!

EDIT: Added backend webforms "service" exposure

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e) 
    {

    }

    [WebMethod]
    public static string TestService(string id) 
    {
        var string = DBCollection.FirstOrDefault(x => x.id == id); // Or whatever you want to return the data
        return "You called me on " + DateTime.Now.ToString() + "with " + string;
    }
}

This would allow you to call the "WebMethod exposed on your page. For more help with this, please see the following link.

http://www.tugberkugurlu.com/archive/asp-net-web-forms---calling-web-service-page-methods-using-jquery

EDIT: Additional Considerations when performing this type of approach in webforms. Calling a webmethod with jquery in asp.net webforms

Community
  • 1
  • 1
David L
  • 32,885
  • 8
  • 62
  • 93
  • Could you also show how this would work in the backend part of it? Also, my website is not MVC. – jmasterx Jan 31 '13 at 14:46
  • @Milo What is your backend? Webforms? Do you have any service endpoints exposed? – David L Jan 31 '13 at 14:47
  • Yes, it is web forms. public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } } – jmasterx Jan 31 '13 at 14:55
  • Thanks, but now I am just wondering, am I then expected to have my whole application in a singleton? How can I get information like the Page Name and such? What is the proper way to get access to instance variables? – jmasterx Jan 31 '13 at 15:03
  • @Milo pageName would be extracted by javascript. It would look at the page you are currently on to determine location. As for the rest of your questions, that's a whole new can of worms on architecture I think – David L Jan 31 '13 at 15:04
  • Well is there anything better than a singleton in this case? Singleton.GetPageInstance().GetPageName(); – jmasterx Jan 31 '13 at 15:07
  • @Milo Is there any reason why your page would NOT be a singleton? If no, I see no harm in it though I'm hardly an expert in Webforms architectural patterns. – David L Jan 31 '13 at 15:13
  • PageLoad for example is an instance method. They are all. I would not know how to make them static. – jmasterx Jan 31 '13 at 15:15
  • @Milo Fair enough. I'd just set up your data "service" methods to requery whatever data set you needed then. The window.location.pathname will always return your current page so I don't think you'll have any worries there. You may just need to refresh data on a per instance basis as opposed to keeping it current in a singleton. – David L Jan 31 '13 at 15:16
  • What do you mean by 'per instance basis'? I will need access to the user's session, so I suppose that will be in a singleton right? Application.GetSession().GetUser().IsAdmin(); I need things like that. – jmasterx Jan 31 '13 at 15:20
  • The calls to this "service" would be on an as-needed basis correct? So anything that would be consumed would just need to be reaccessed within that method. – David L Jan 31 '13 at 15:22
  • I really do appologize but, I did not understand what you just wrote. – jmasterx Jan 31 '13 at 15:24
  • Sorry, not sure how to explain it well. If you needed something like Application.GetSession().GetUser().IsAdmin();, call it from inside the WebMethod TestService() and consume it as you need. Even if your session is a singleton, you can still just re-access it each time you hit the WebMethod – David L Jan 31 '13 at 15:26