Mr. Blond
Mr. Blond

Reputation: 1167

Check if view model property has value in Javascript using MVC Razor syntax

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

Answers (3)

Mosijava
Mosijava

Reputation: 4169

you can simply use this:

var year = @(@Model.Year??0)

Upvotes: 1

Shyju
Shyju

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

Kartik Jethani
Kartik Jethani

Reputation: 9

Use @Model.Year.HasValue to check for nulls.

var year2 = @Model.Year.HasValue ? @Model.Year.Value : 0;

Upvotes: 0

Related Questions