How can I do a call back to the code behind method using javascript (properly)?

梦想的初衷 提交于 2021-02-11 12:49:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!