Reputation: 1167
How do I get value from view model in Javascript if the property is nullable like int?
, bool?
etc.
I easily managed to check if property has a value, it works until I return it's value.
<script type="text/javascript">
// Works as expected
var year = !!'@Model.Year' ? 1994 : 0;
// Null reference exceptin thrown
var year2 = !!'@Model.Year' ? @Model.Year.Value : 0;
</script>
For some reason the condition is ignored when returning property using razor syntax. The same happens if use if
and else
statements.
Edit:
The exception is thrown also if using @Model.Year.HasValue.ToString().ToLower()
to check for null value.
Upvotes: 2
Views: 9546
Reputation: 218722
You can use the HasValue
property on the nullable int variable to determine whether it has value or not, If yes, read the value, else set the default value you want. You can do this in one c# statement so that you do not need to worry about True
and true
inconsistencies between C# and javascript.
This should work fine.
<script>
var year = @(Model.Year.HasValue ? Model.Year.Value : 0);
alert(year);
</script>
Here we wrapped the entire expression as a single C# statement by wrapping it in @(
and )
. So when this page is loaded, razor will run the C# statement and set the resulting value to your javascript variable.
Upvotes: 6
Reputation: 9
Use @Model.Year.HasValue
to check for nulls.
var year2 = @Model.Year.HasValue ? @Model.Year.Value : 0;
Upvotes: 0