简体   繁体   English

混合Razor和Javascript:在视图中为Model分配一个数字给Javascript变量

[英]Mixing Razor and Javascript: Assigning a number from Model to a Javascript variable in a view

I'm having difficulties to assign just a basic number from Model to a Javascript variable via Razor. 我很难通过Razor仅将Model的基本数字分配给Javascript变量。 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');

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): 或更好的方法是,使用方括号使Razor部分明确(因此很明显分号是Javascript分号):

var MyNumber = @(Model.MyNumber);

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: 如果您坚持要消除Visual Studio错误,则将Razor模板部分包装在一个身份函数调用中可以起作用,而花费的费用比解析要低:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM