I hope this is not a duplicate post.
I have searched internet on how to find out if a model is null in jQuery. There are plenty of examples. I have tried many of them. However, I keep getting problem for this particular issue
Here are the pseudo codes
//class declaration
public class class2
{
public int var1 { get; set; }
public int var2 { get; set; }
}
public class class1
{
//other properties
public class2 InnerClass { get; set; }
}
//controller
class1 CLASS1 = GetClass1()
class1= GetClass1()
CLASS1.class2 = NULL
//VIEW
@model class1
//java script
var isObjectNotnull = @(Model.InnerClass != null );
var x;
if (isObjectNotnull )
x = @(Model.InnerClass.var1);
else
x = -1;
The error happens in this line
x = @(Model.InnerClass.var1);
I got this error
Object reference not set to an instance of an object.
I thought these two statements will solve the problem
var isObjectNotnull = @(Model.InnerClass != null );
if (isObjectNotnull )
Obvious, it does not help
Then I comment out the assignment
if (isObjectNotnull )
alert('a');
@*x = @(Model.InnerClass.var1);*@
Looks like Javascript will render everything. Since Model.InnerClass is null, Javascript cannot continue to render
What is the best approach.
Oh, I need that variable X as part of jSon variable in Ajax variable. Originally, Model.InnerClass.var1 is assigned to jSon variable. Then I got the error, so I added the codes to check for null object, and I still could not resolve this hurdle
Thanks