How to call a c# method in javascript function directly. (eg page_load
method of code behind page). Please help me.
相关问题
- Is there a limit to how many levels you can nest i
- Sorting 3 numbers without branching [closed]
- How to toggle on Order in ReactJS
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
You can create an ASHX handler where the C# method you want to run is executed and then use AJAX/jQuery to call the handler.
Simple answer: YOU CANNOT (at least page_load specifically)! Get clear understanding about what is server-side and what is client side code.
Other options to call server side methods is using AJAX! Read.
I don't know about c# in particular, but a good way for your client-side to comunicate with your server-side is through a RPC (Remote Procedure Call) implementation.
Lets say that you use JSON-RPC.
First, you create your json object that represents the request :
where the method represents the function name that you are calling,
the params represent an aray of parameters that the specified function should take,
and id is an unique identifier for requested objects.
Then you want to send this request to the server. This should be done with ajax. Suppose you have a function that handles ajax requests called
sendAjaxRequest
that takes 3 parameters :a callback to handle the response
The server recieves the request, interprets it and executes the method with the desired params and constructs a response json object :
and send it back to the client.
This is a very good practice, no matter the situation.
You have multiple choices and each choice has its own pros and cons.
window.location.reload()
and the load event of your page will be called.jQuery
or Ajax.Net Professional or ASP.NET Ajax's update panel.I would use a web method, if you want to call a method in C# from JavaScript. An example is provided below. I hope this is of some help.
ASP.NET - The following HTML Markup consists of an ASP.Net TextBox and an HTML Button.
JavaScript Code: - When the Button is clicked the ShowCurrentTime JavaScript function is executed which makes an AJAX call to the GetCurrentTime WebMethod. The value of the TextBox is passed as parameter to the WebMethod.
The WebMethod - The following WebMethod returns a greeting message to the user along with the current server time. An important thing to note is that the method is declared as static (C#), this is necessary otherwise the method will not be called from client side jQuery AJAX call.
C#
javascript would be client side and page_load would be serverside . I don think you can call the method as such. May be you can create a separate page just for that method and make a call via ajax