javascript - 如何在javascript中处理空 session

标签 javascript jquery html

有没有办法摆脱这个错误。我知道它是空的,但我已经在其中放入了 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/

相关文章:

javascript - JS 选择的元素在 css 菜单中没有正确显示

jquery - 最佳实践 : Temporary Record with has_many association

javascript - 在 html 表中的两个字段之间画线?

jquery - 如何将 div 框相互定位

javascript - 减少使用 Web Essentials

javascript - 使用 Gulp 在同一目录中的多个文件扩展名

c# - 为什么 "dtoa.c"包含这么多代码?

javascript - Webpack React 外部不工作

javascript - 无法使用复选框切换多个动态 Google map 标记点

javascript - Web Components 中的路径是相对于 Root 的