2

I'm having difficulties to assign just a basic number from Model to a Javascript variable via Razor. All that I came up with was the code below, which works, but is rather ugly as I have to convert the string value into a number. Is there any other way to just get it right away in the numeric format without any conversions?

var MyNumber = parseInt('@Model.MyNumber');
2

2 Answers 2

4

You should be able to do this:

var MyNumber = @Model.MyNumber;

or better, use the brackets to make the Razor part explicit (so it's clear that the semicolon is a Javascript semicolon):

var MyNumber = @(Model.MyNumber);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, it worked nicely. I actually tried your suggestions before but I didn't test the output as my Visual Studio 2012 is giving a syntax error (warning) in both cases (maybe a bug?). I guess I have to stop paying attention to what Visual Studio is saying and just code.
@user405723 VS2012 is reporting a syntax error for me on this exact thing too - looks like a common issue - stackoverflow.com/a/12559317/300685
It's a bug in VS2012 and VS2013. I sent a bug report to Microsoft and they answered that "it's a very complicated issue to solve". I don't know about you guys but recently I've begun to think that the quality control of Visual Studios has slipped away.
2

If you insist in eliminating the Visual Studio error, wrapping the Razor template part in an identity function call works, at a lower cost than the parse:

var noop = function(x) { return x; }
var MyNumber = noop(@Model.MyNumber);

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.