Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set javascript variables using MVC4 with Razor

Can someone format the code below so that I can set srcript variables with c# code using razor?

The below does not work, i've got it that way to make is easy for someone to help.

@{int proID = 123; int nonProID = 456;}  <script type="text/javascript">     @{       <text>        var nonID =@nonProID;     var proID= @proID;     window.nonID = @nonProID;     window.proID=@proID;      </text> } </script> 

I am getting a design time error

enter image description here

like image 880
Filling The Stack is What I DO Avatar asked Feb 14 '13 01:02

Filling The Stack is What I DO


People also ask

How do you declare variables in razor?

To declare a variable in the View using Razor syntax, we need to first create a code block by using @{ and } and then we can use the same syntax we use in the C#. In the above code, notice that we have created the Code block and then start writing C# syntax to declare and assign the variables.

How do I run JavaScript on a razor page?

Calling JavaScript Function from Razor View To include a JavaScript function, it is as simple as include a <script> tag and define the function inside the script block. Now, to call the function, add an onclick event on the employee name hyperlink and call the function.


2 Answers

You should take a look at the output that your razor page is resulting. Actually, you need to know what is executed by server-side and client-side. Try this:

@{     int proID = 123;      int nonProID = 456; }  <script>      var nonID = @nonProID;     var proID = @proID;     window.nonID = @nonProID;     window.proID = @proID;  </script> 

The output should be like this:

enter image description here

Depending what version of Visual Studio you are using, it point some highlights in the design-time for views with razor.

like image 184
Felipe Oriani Avatar answered Sep 24 '22 15:09

Felipe Oriani


Since razor syntax errors can become problematic while you're working on the view, I totally get why you'd want to avoid them. Here's a couple other options.

<script type="text/javascript">     // @Model.Count is an int     var count = '@Model.Count';     var countInt = parseInt('@Model.ActiveLocsCount'); </script> 

The quotes act as delimiters, so the razor parser is happy. But of course your C# int becomes a JS string in the first statement. For purists, the second option might be better.

If somebody has a better way of doing this without the razor syntax errors, in particular maintaining the type of the var, I'd love to see it!

like image 23
Sean Avatar answered Sep 22 '22 15:09

Sean