[英]Why my session value changed for a particular value?
Can someone help understand why my session value changed for a particular value, 03375? 有人可以帮助理解为什么我的会话值更改为特定值03375吗?
My MVC controller code: 我的MVC控制器代码:
Session["something"] = "03375";
My view js code: 我的视图js代码:
$(function(){
alert(@Session["something"].ToString());
});
Result: js alerts 1789. Why??? 结果:js警报1789。为什么?
It works for other values except. 它适用于其他值。 Here is a fiddle https://dotnetfiddle.net/zLdyO8
这是一个小提琴https://dotnetfiddle.net/zLdyO8
This has nothing to do with asp.net session. 这与asp.net会话无关。 If you do this in your page
如果您在页面中执行此操作
console.log(03375);
You will get 1789
你会得到
1789
Why is this happening ? 为什么会这样呢?
Because when browser's javascript runtime sees a number starting with 0
prefix, it thinks it is octal representation of the number. 因为当浏览器的javascript运行时看到以
0
前缀开头的数字时,它会认为它是数字的八进制表示形式。 In fact 03375
is the octal equivalent of 1789
. 实际上
03375
是1789
的八进制等效项 。 So your browser is basically converting the octal value to it's decimal equivalent and giving you 1789
( browsers usually parse the number to decimal representation ) 因此,您的浏览器基本上将八进制值转换为其等效的十进制值,并给您
1789
( 浏览器通常将数字解析为十进制表示形式 )
Note that decimal literals can start with a zero (0) followed by another decimal digit, but if every digit after the leading 0 is smaller than 8, the number gets parsed as an octal number.
请注意,十进制文字可以以零(0)开头,后跟另一个十进制数字,但是如果前导0之后的每个数字都小于8,则该数字将被解析为八进制数字。
This means, if you are trying 这意味着,如果您正在尝试
console.log(09375);
It will print, 9375
!!! 它将打印出
9375
!!!
To handle your case, the ideal solution is to set the correct type value. 要处理您的情况,理想的解决方案是设置正确的类型值。 For example, if you are passing a numeric value, simply set the numeric value instead of the string version with leading zero..
例如,如果要传递数字值,则只需设置数字值,而不是前导零的字符串版本。
Session["something"] = "3375";
Or even better 甚至更好
Session["something"] = 3375;
Then in the client side, 然后在客户端,
alert(@Session["something"]);
If you absolutely want to keep the 0
prefix, while setting the session value, but you want the value as number at client side, you can read it in a string and then use parseInt
to convert it to a number type 如果您绝对要在设置会话值时保留
0
前缀,但希望将该值作为客户端的数字,则可以在字符串中读取它,然后使用parseInt
将其转换为数字类型
var r = '@Session["something"].ToString()';
alert(r); // the string with leading 0
var n = parseInt(r);
alert(n); // the number
alert(typeof(n));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.