问题
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');
回答1:
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);
回答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);
来源:https://stackoverflow.com/questions/19089671/mixing-razor-and-javascript-assigning-a-number-from-model-to-a-javascript-varia