views:

45

answers:

2

I have a java-script function that displays options on a web page and a C# function that stores preferences in a database. I need some way for said java-script to also execute my C# function. I think this is possible with AJAX, but I am not entirely sure (I've never used AJAX before). I've read some tutorials (w3schools), however none of them make use of C# code-behind files. Reading SO, I found this, but I could not get it working either. If what I am doing is even possible, could some one help walk me through it, or point me in the right direction?

+1  A: 

You may be able to use the Microsoft AJAX / UpdatePanel, but I've not used that and any implementations I have seen have been frought with problems later on down the line.

Otherwise take a look at Jquery AJAX. That can help making the single AJAX call you are interested in. Then it may be quicker / easier to make a web service method that you can call directly from AJAX and abstract the code in question out, so it is possible to use in both your server side ASPX code and your client side JS code.

Paul Hadfield
Thanks, I'll check that out.
0_o
A: 

To elaborate on the UpdatePanel approach, you could do the following:
1. Add an UpdatePanel to your page.
2. Inside the UpdatePanel, add a Button. Style it to be not visible. Add an OnClick handler to the button that calls your C# code.
3. In your JavaScript, add code to click the hidden button

<asp:UpdatePanel ID="MyUpdatePanel" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Button ID="HiddenButton" runat="server" Text="" OnClick="HiddenButton_Click" Style="display: none;" UseSubmitBehavior="False" />
     </ContentTemplate>
</asp:UpdatePanel>

function MyJavaScript() {
    var hiddenButton = $get("<%=HiddenButton.ClientID %>");
    if (hiddenButton != null) {
       hiddenButton.click();
    }
}
Andrew