Gabriel Lemelle Gabriel Lemelle - 1 year ago 76 Question

Null Error when checking null value

I am trying to test values before doing some actions with session variables.
This is for initializing( As you can see Session("Chemin") is a List of String:

@If (IsDBNull(Session("Chemin")) Or (ViewContext.RouteData.Values("action") = "Index")) Then
@Code Dim lst As New List(Of String)()
Session("Chemin") = lst // Initialisation
End Code
End If

But the problem is with the test here :

@If (Not IsDBNull(ViewContext.RouteData.Values("action")) AndAlso Not IsDBNull(Session("Chemin")) AndAlso Not Session("Chemin").Contains((ViewContext.RouteData.Values("action").ToString()))) Then

I sometimes get


I don't understand because I am just testing it, and yet it throws me an error.
So my question is : Why and when exactly does it happens ? How to fix this ?
Edit: not a duplicate because not a simple System.NullReferenceException

Answer Source

You should replace all your IsDBNull with IsNothing, that is what you are looking for in this case. Because I think your

    @If (IsDBNull(Session("Chemin"))

could not pass and so the Session("Chemin") could be Nothing.

You should check that ViewContext, ViewContext.RouteData , ViewContext.RouteData.Values and ViewContext.RouteData.Values("action") are not nothing just in case.

You can do it with this :

                                                @Code Dim values = ViewContext?.RouteData?.Values End Code
                                        @If (values IsNot Nothing) // And the rest of your tests
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download