问题
So I am trying to call back to a code behind method using Javascript and it seems like the only way to do so is using the
Page.ClientScript.RegisterClientScriptBlock()
Method.
I don't need to return any data back to the calling javascript function.
This isn't a web service, so I am not going to use a ajax call, but this seems like there would be an easier way to do this than Client Callbacks Programmatically with Page.ClientScript.....
回答1:
Page.ClientScript.RegisterClientScriptBlock() is just used to push some JavaScript code block in your page. This is not intended to call server method. If you want to call server code from JavaScript, you should check for the [WebMethod] attribute. Basically, you put that attribute on top of a public static method of your page, and you can call it in JavaScript.
C# Example:
[WebMethod]
public static void MyWebMethod(string foo)
{
doSomething(foo);
}
VB.NET Example:
<WebMethod>
Public Sub MyWebMethod(foo As String)
doSomething foo
End Function
And then, in JavaScript:
<script type="application/javascript">
PageMethods.MyWebMethod(someValue);
</script>
And you're done.
来源:https://stackoverflow.com/questions/5264642/how-can-i-do-a-call-back-to-the-code-behind-method-using-javascript-properly