0

I have read Object reference not set to an instance of an object. and What does “Object reference not set to an instance of an object” mean? posts but still not able to get help because my case is different.

Simple Code

<script>
   var PatientId;
   var DoctorId;

   if(isPatient && @Model.Patient != null) {
        PatientId = @Model.Patient.Id;
        DoctorId = userConnection.User.Id;
   } else if(!isPatient && @Model.Doctor != null) {
        DoctorId = @Model.Doctor.Id; // Right here I get ERROR
        PatientId = userConnection.User.Id;
   }
</script

Error

System.NullReferenceException: Object reference not set to an instance of an object.

In my case either @Model.Patient or @Model.Doctor will be null.

Right now I know that @Model.Doctor is null, but I am already checking its null condition above. How to cater this problem ?

Community
  • 1
  • 1
Junaid
  • 2,572
  • 6
  • 41
  • 77
  • Why the double && &&?
    } else if(!isPatient && && @Model.Doctor != null) {
    – Ivaylo Stoev Jan 22 '17 at 14:56
  • @IvayloStoev Sorry its typo. It not in original code. – Junaid Jan 22 '17 at 14:57
  • On which line you are getting the exception? How isPatient is initialized? – Chetan Jan 22 '17 at 15:01
  • From backend Patient is initialized while doctor is null. – Junaid Jan 22 '17 at 15:03
  • @ChetanRanpariya DoctorId = @Model.Doctor.Id; // Right here I get ERROR – Junaid Jan 22 '17 at 15:04
  • Model.Doctor is null. As far as i can see you are generating javascript code in the view from the model. This code is not getting executed so you never check if Model.Doctor is null – Ivaylo Stoev Jan 22 '17 at 15:05
  • @IvayloStoev exactly. So is there any work around to this ? – Junaid Jan 22 '17 at 15:09
  • You can not mix javascript (executed on the client) and c# code executed on the server) like that. You can use the Model to help you generate javascript code but not check against the model like that. – Ivaylo Stoev Jan 22 '17 at 15:13
  • 2
    Not sure why this was marked as duplicate. I understand that the Exception is the same as the other questions but the context is different here. Solution of this particular case would be different based on the given situation. – Chetan Jan 22 '17 at 15:35
  • 1
    @Junaid you need to create server side variables at the top of the view and assign their values to the JS variables in your script block. Script block should be after the variable declaration. Then you check the values of the JS variables to have your logic further. @{ var patientId = Model.Patient != null ? Model.Patient.Id : 0; var doctorId = Model.Doctor != null ? Model.Doctor.Id : 0; } – Chetan Jan 22 '17 at 15:37
  • @ChetanRanpariya This one worked. Thanks – Junaid Jan 22 '17 at 18:16

0 Answers0