Can someone help understand why my session value changed for a particular value, 03375?
My MVC controller code:
Session["something"] = "03375";
My view js code:
$(function(){
alert(@Session["something"].ToString());
});
Result: js alerts 1789. Why???
It works for other values except. Here is a fiddle https://dotnetfiddle.net/zLdyO8
This has nothing to do with asp.net session. If you do this in your page
console.log(03375);
You will get 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. In fact 03375
is the octal equivalent of 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)
From mdn,
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.
This means, if you are trying
console.log(09375);
It will print,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
var r = '@Session["something"].ToString()';
alert(r); // the string with leading 0
var n = parseInt(r);
alert(n); // the number
alert(typeof(n));