2

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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Found a way how to write in multiple lines. For Javascript just need to use @: like this: var someVar = 0;@if(Model.Year.HasValue){@:someVar = '@Model.Year.Value';}else if(Model.Year2.HasValue){ @:someVar = '@Model.Year2.Value';}
1

you can simply use this:

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

Comments

0

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

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

1 Comment

This will not work as in c# boolean value is True or False whereas in Javascript true or false. It would work if you put @Model.Year.HasValue.ToString().ToLower() @Kartik Jethani.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.