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?
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?
- 2 Session["myIndex"] returns null, and null does not have an .Equals() function. You need to pare with ==, as that is not a function that needs an object to derive from. – Corey Commented May 5, 2010 at 10:22
5 Answers
Reset to default 3The 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 pare value so you can use it you want to pare like (Session["myIndex"]).Equals("yourIndex")
Are you sure Session["myIndex"]
isn't null?
You should add another short circuit OR check for (Session["myIndex"] == null)
and get rid of (Session["myIndex"]).Equals(null)
.
This will work (I have tested it!):
var myIndex = <%=!string.IsNullOrEmpty( (string)Session["myIndex"] ) ? Session["myIndex"] : "1" %> ;
in the code behind create a protected variable and initialize it there. The main advantage is that you can debug it there. And in plus you can use try catch.
code-behind
protected string sessionValue;
private void Page_Load(...)
{
try
{
sessionValue = Session["key"].ToString();
}
catch
{
sessionValue = [defaultValue];
}
}
javascript:
<script>
var sessionValue = "<%= sessionValue %>";
</script>
This way you can avoid the crash and do something else if the sessionValue is null or has a defaultValue.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745433700a4627511.html
评论列表(0条)