0

I have an asp.net core MVC application, and I'm using an if statement for conditional rendering.

In the following code snippet:

if (@item.Date.HasValue)
{
    <div>
        <text>@Common.DateConverter.GetHijriDateString(item.Date.Value)</text>
    </div>
}

Why is it throwing a (InvalidOperationException: Nullable object must have a value.) exception, if the value is null, even though I have placed a check for null value in the enclosing if statement?

1 Answer 1

1

Your Razor expression is wrong. Your if didn't start with an @ so it's just a HTML not the razor. So even though @item.Date.HasValue would run fine, it will fail on the GetHijriDateString parameter item.Date.Value when the date doesn't have a value.

To fix it:

@if (item.Date.Hasvalue)
{
    ...
}

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

Comments

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.