How do I do #nullable enable in an aspnetcore razor view page (.cshtml)

Viewed 1782

Possible Duplicate, but I've been unable to find anything on this.

I have an asp.net core MVC project, which makes use of normal views using Razor.

I have some ViewModel objects with nullable reference types, and I'm using the C# 8 null-safety feature to mark those appropriately (e.g. string? Name)

My problem is, when I use those variables in a cshtml file, as strongly typed Models, the null-safety isn't applied because I haven't enabled it for the file.

If it were a .cs file, I'd stick #nullable enable at the top, but what can I do for razor pages?


Update to clarify: If possible, I would like null-safety warnings on all @code blocks throughout the razor file. Tân's answer shows how to enable it for a specific block, but I'd like it for something like this

<span>@Model.Name.ToUpper()</span>

Specifically, I'd like a warning on Name.ToUpper() as Name is nullable and I didn't use the ? operator when calling ToUpper

1 Answers

There isn't enough information in your question to say what you need to do (such as: adding some package(s), removing some package(s)...)

But by default, Razor syntax supports for #nullable, you can use it inside @{} block.

Example:

@{
    #nullable enable
    string name1 = User.Identity.Name.ToLower();
    #nullable disable

    // compiler won't complain anything here...
    string name2 = User.Identity.Name.ToLower();
}

Test:

1

My csproj file what I've used to test:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

</Project>
Related