1

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?

0

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

The server code will get processed first, before the page is ever rendered. So you'd have to use something like AJAX to pass a JavaScript value back to the server.

Comments

0

Since it is your server code that gives the object an @id, the server should already know it at the point of creation. But no, you can't interleave client and server like that - they run disjoint in time and geography

Comments

0

You can't do this because the server variable will have already been calculated and the HTML has been generated by the time the client script runs.

Server Side Code Runs => Generated HTML File Served To Browser => Javascript Code Runs

This process is one-way, so there's not a way to give that variable back without using an Ajax request.

However, if all you need is the id, and the control is a .NET control, you can simply use the myControl.ClientID value.

Comments

0

To send data from browser to server you should use form controls (text field, hidden field, textarea, checkbox, etc.) or ajax. In your case, you can serialize javascript object to a string and pass it to the server via hidden field or XmlHttpRequest.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.