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

一个人想着一个人 提交于 2021-01-28 01:04:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!