1

I would like to access a c# variable value inside a javascript function whose code is similar to this snippet below:

@{ var i=0; }

....

<script type="javascript">

function MyObjects(e) {

for (j = 0; j <= @i; j++) {....}

</script>

..... { i=@i+1;}

3
  • This is not even wrong. What exactly are you trying to accomplish? Commented Jul 30, 2012 at 15:34
  • when I access i value inside javascript, I can just find its value as 0, instead of updated value. Commented Jul 30, 2012 at 15:34
  • I understand it doesn't work, but what are you trying to do? Why are you trying to do it? Commented Jul 30, 2012 at 15:36

2 Answers 2

3

You can't "access" a C# variable from JavaScript because the C# code runs on the server side to render HTML, and the HTML including the generated JavaScript runs in the client browser.

If you want to render the value of a C# variable into the JavaScript code that runs on the client, your code

for (j = 0; j <= @i; j++) {....}

does just that.

However, if you expect

{ i=@i+1;}

to run on the client and affect the state on the server, it will not.

Solution

If you need to update the state of something on the server from JavaScript without posting the HTML page back to the server, you can do that with an Ajax callback.

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

Comments

1

You can get C#/Razor values as a string easily enough.

<script type="text/javascript">
    var i = parseInt("@i");
</script>

1 Comment

Thanks all. I got what i want.

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.