Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a value through a Session variable

I need to Initialize a value in a Javascript by using a c# literal that makes reference to a Session Variable. I am using the following code

<script type="text/javascript" language="javascript" > 
    var myIndex = <%= !((Session["myIndex"]).Equals(null)||(Session["myIndex"]).Equals("")) ? Session["backgroundIndex"] : "1" %>;

However the code above is giving me a classic Object reference not set to an instance of an object. error. Why? Shouldn't (Session["myIndex"]).Equals(null) capture this particular error?

like image 418
William Calleja Avatar asked Nov 05 '22 13:11

William Calleja


2 Answers

The problem is that null isn't an object, and the Equals() method can only be used on objects. If you want to check if your Session object is null, you should use (Session["myIndex"] == null). You can also use string.IsNullOrEmpty() for an additional check on empty strings. In that case, your code should be:

var myIndex = <%= !string.IsNullOrEmpty((string)Session["myIndex"]) ? Session["backgroundIndex"] : "1" %>;

Note: Shouldn't Session["backgroundIndex"] be Session["myIndex"] in this case? Otherwise the null or empty string check is a bit useless in my opinion.

like image 172
Prutswonder Avatar answered Nov 14 '22 22:11

Prutswonder


object reference error may be because (Session["myIndex"]) is null,

(Session["myIndex"]).Equals is used to compare value so you can use it you want to compare like (Session["myIndex"]).Equals("yourIndex")

like image 24
Vinay Pandey Avatar answered Nov 14 '22 22:11

Vinay Pandey