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?
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With