Search code examples
c#javascriptasp.net.netinline-code

Pass parameters to code behind function using JavaScript


I'm trying to call a code-behind function inside JavaScript and pass a parameters to the code-behind function.

For example:

<script> 
var name; 
<% createUser(name) %> 
</script>

private void createUser(string Name)
{ // Do crazy stuff }

I'm doing this because some of the elements are dynamically created using jQuery, so I cannot access them in server side code. The example above is relatively simple and nothing close to what I'm trying to achieve, nevertheless, it does give you a good overview of my problem.

Thanks!


Solution

  • You can't directly "call" a code-behind function from JavaScript. JS runs in the client's browser, and C# is running on a server somewhere else. The two communicate using HTTP requests via the medium of a web server. You can fire off an HTTP Request from the client, and have a server page waiting to process such requests by delegating to code-behind functions: