通过会话变量初始化值
我需要使用引用会话变量的 ac# 文字来初始化 Javascript 中的值。我正在使用以下代码
<script type="text/javascript" language="javascript" >
var myIndex = <%= !((Session["myIndex"]).Equals(null)||(Session["myIndex"]).Equals("")) ? Session["backgroundIndex"] : "1" %>;
,但是上面的代码给了我一个经典的对象引用未设置为对象的实例。
错误。为什么? (Session["myIndex"]).Equals(null)
不应该捕获此特定错误吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
问题是
null
不是对象,而Equals()
方法只能用于对象。如果您想检查 Session 对象是否为 null,则应使用(Session["myIndex"] == null)
。您还可以使用 string.IsNullOrEmpty() 来对空字符串进行额外检查。在这种情况下,您的代码应该是:注意: 在此
Session["backgroundIndex"]
不应该是Session["myIndex"]
案件?否则,在我看来,空或空字符串检查有点无用。The problem is that
null
isn't an object, and theEquals()
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 usestring.IsNullOrEmpty()
for an additional check on empty strings. In that case, your code should be:Note: Shouldn't
Session["backgroundIndex"]
beSession["myIndex"]
in this case? Otherwise the null or empty string check is a bit useless in my opinion.对象引用错误可能是因为 (Session["myIndex"]) 为 null,
(Session["myIndex"]).Equals 用于比较值,因此您可以像 (Session["myIndex"]) 一样使用您想要比较的它.Equals("yourIndex")
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")
您确定
Session["myIndex"]
不为空吗?您应该添加另一个短路或检查
(Session["myIndex"] == null)
并删除(Session["myIndex"]).Equals(null)
。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!):
在后面的代码中创建一个受保护的变量并在那里初始化它。主要优点是您可以在那里调试它。另外你可以使用 try catch。
代码隐藏
javascript:
这样,如果 sessionValue 为 null 或具有 defaultValue,您可以避免崩溃并执行其他操作。
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
javascript:
This way you can avoid the crash and do something else if the sessionValue is null or has a defaultValue.