Call a Javascript Method from code-behind Web Method
I have a web method in my code behind:
[System.Web.Services.WebMethod]
public static string GetStateData(string state)
{
//this is where i want to call a javascript method "GetItems"
}
I have a javascript method that retrieves some values for me and I want to get use one of those values in my web method
function GetItems() {
var variable1= $("#<%=Item1.ClientID %> input:checked");
开发者_开发知识库var variable2= $("#<%=Item2.ClientID %>").val();
return [variable1.text(), variable2.val(), variable2];}
I've searched for ways to call the javascript method from the web method but every time my search results in how to call a web method from javascript.
I did find this but it was done from the code-behind of a silverlight project and when I tried adding the correct reference to my code-behind it wasn't there
var result = HtmlPage.Window.Invoke("GetItems");
Is there a reference I'm missing?
Thanks for your response
You can't do that. Your calling a webmethod through AJAX. your sending small pieces of information to a static method on the server that knows nothing about the specific page object (That isn't static).
What you want to do is send those values and data in the AJAX call to the webmethod. Your not making a full postback so you know nothing about the current state of the page except what you pass as paramaters to the webmethod.
Either send the information in the first place or return with some kind of flag when you want the information and get the client to make an ajax call back to another function with the information and let it continue from there.
Instead of trying to call javascript from a webmethod use the return value of the webmethod to decide what javascript function to call.
Calling javascript from a webmethod is not possible as far as I know - you need to understand the distinction between server side and client side code.
精彩评论