有没有办法摆脱这个错误。我知道它是空的,但我已经在其中放入了 try catch ,为什么它仍然显示错误以及它是否为空的条件,但错误仍然显示我的 session 为空。 这是我的代码:
try {
if ('<%=Session["Selected"].ToString()%>' == null) {
loadTimesheetgrid();
}
else {
if ('<%=Session["Selected"].ToString()%>' == 'More Than 60 Hrs') {
//call the script you will make for morethan 60 hrs
}
else {
loadTimesheetgrid();
}
}
}
catch (error) {
loadTimesheetgrid();
}
错误显示:
System.NullReferenceException: Object reference not set to an instance of an object.
最佳答案
如果您的 session 值为 null,则在 .ToString() 时将无法转换它 因此,最好先检查它是否为 null 或者是否有某个值,如果有,则只尝试将其转换为字符串。
if ('<%=Session["Selected"]%>' != null)
{
if ('<%=Session["Selected"].ToString()%>' == 'More Than 60 Hrs')
{
//call the script you will make for morethan 60 hrs
}
else {
loadTimesheetgrid();
}
}
else {
loadTimesheetgrid();
}
我建议您不要在 View 文件中放置 try 和 catch block ,因为有时如果失败,它会加载部分 html 元素,并且您可能会遇到一些对齐问题。但是,您可以选择将代码包装在 try 和 catch block 中。
try
{
if ('<%=Session["Selected"]%>' != null)
{
if ('<%=Session["Selected"].ToString()%>' == 'More Than 60 Hrs')
{
//call the script you will make for morethan 60 hrs
}
else {
loadTimesheetgrid();
}
}
else {
loadTimesheetgrid();
}
}
catch(error)
{
loadTimesheetgrid();
}
关于javascript - 如何在javascript中处理空 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58317973/