Search code examples
c#javascriptclient-sideserver-sideinline-code

Mixing javascript and inline server code


I am trying to do the following:

   <script>
      var documentId = %(this).attr('id');

      <% int docId = %>documentId<%;%>

   </script>

As you can see, I'm trying to create a new server variable but assign the value of the javascript variable. Or at least have the javascript variable evaluated. (This is a simplied example of the real world problem I'm trying to solve) Is there any way that I can do this?


Solution

  • The problem:

    1. Server-side code is evaluated on the server, before anything is transmitted to the client.
    2. Client side code (JavaScript) is evaluated in the browser, after the server has finished transmitting the document.

    After understanding the above statements, you'll see that your current example is technically impossible.

    What you will need to do (if your goal is to prevent a page refresh) is send the new data to a script on the server using AJAX. The script will process the data and respond to the browser.