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
I use a very simple
function
to solve syntax errors in body ofJavaScript
codes that mixed withRazor
codes ;)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
andclient-side
. Try this:The output should be like this:
Depending what version of Visual Studio you are using, it point some highlights in the design-time for views with razor.
Not so much an answer as a cautionary tale: this was bugging me as well - and I thought I had a solution by pre-pending a zero and using the
@(...)
syntax. i.e your code would have been:Getting output like:
What I didn't realise was that this is how JavaScript (version 3) represents octal/base-8 numbers and is actually altering the value. Additionally, if you are using the
"use strict";
command then it will break your code entirely as octal numbers have been removed.I'm still looking for a proper solution to this.
It works if you do something like this:
Which produces code that is something like:
A bit odd for sure, but no more fake syntax errors at least. Sadly the errors are still reported in VS2013, so this hasn't been properly addressed (yet).
I've been looking into this approach:
To me this seems to make it safer on the JS side... worst case you end up with a null variable.
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.
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!