I am a bit stumped with the following code. It worked fine in VS2010 on Windows 7, and now that I've upgraded the hardware to Windows 8 and VS 2012, it does not.
I have the following JavaScript code in my MVC application:
<script language="javascript" type="text/javascript">
var today;
if("@Model.Birthday.HasValue"){
var today = new Date("@Model.Birthday.Value.Year", "@Model.Birthday.Value.Month" - 1, "@Model.Birthday.Value.Day");
}else{
today = new Date();
}
The Model is pulling from a ViewModel that has a property that looks like this:
public System.DateTime? Birthday
{
get { return user.Birthday; }
set { user.Birthday = value; }
}
The exception is thrown in the line:
var today = new Date("@Model.Birthday.Value.Year", "@Model.Birthday.Value.Month" - 1, "@Model.Birthday.Value.Day");
It comes back with "Nullable object must have value", which it should if it jumps in that line to execute. But, my if statement is returning false. If I remove the line and just put in an alert statement, it never executes that line or shows the alert, because the Birthday property is null. Something seems to have shifted in how JS executes MVC code, and it seems to evaluate the entirety of the code block, regardless of the if statement. I've also tried the following, but to no avail:
- Tested in Chrome for W8
- Tested in a try / catch block. Interestingly, it doesn't catch the exception (I guess JS won't catch .NET exceptions)
- Tested by explicitly stating @Model.Birthday.HasValue == true
- Tested by changing it to @Model.Birthday.Value != null
- Tested in Release mode over Debug Mode
This should be simple - test to see if a value is null, and if it's not, create a JS Date object from the .NET property, if it is, create a new JS Date object, but for some reason, it want's to evaluate and execute that line, even though HasValue is false.
Really stumped. Has anyone seen something like this?