Home > other >  Several compiler errors in Razor code, that disappear when changing order of unrelated lines
Several compiler errors in Razor code, that disappear when changing order of unrelated lines

Time:07-12

Im using Microsoft Visual Studio Community 2022 (64-bit), Version 17.2.4 and .net core 6.

In the .cshtml file I'm trying to check if ViewData["x"] is null or not like this:

@using System.Collections
@{
    ViewData["Title"] = @Localizer["Title"];
    var list = ViewData["EmailTypes"] != null ? (IEnumerable<SelectListItem>)ViewData["EmailTypes"] : null;
}

Im getting this errors:

Severity Code Description Project File Line Suppression State Error (active) CS0119 'IEnumerable' is a type, which is not valid in the given context X

Severity Code Description Project File Line Suppression State Error (active) CS1026 ) expected

Severity Code Description Project File Line Suppression State Error (active) CS1003 Syntax error, ':' expected

Severity Code Description Project File Line Suppression State Error (active) RZ1025 The "SelectListItem" element was not closed. All elements must be either self-closing or have a matching end tag.

Severity Code Description Project File Line Suppression State Error (active) RZ1006 The code block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.

enter image description here


But if I do like this:

@using System.Collections
    @{
        var list = ViewData["EmailTypes"] != null ? (IEnumerable<SelectListItem>)ViewData["EmailTypes"] : null;
        ViewData["Title"] = @Localizer["Title"];
    }

all errors disappear enter image description here

how come this happens, and whats the best way to check if IEnumerableViewData["x"] is null or not?

CodePudding user response:

ViewData["Title"] = @Localizer["Title"];

There's a "lost"(?) @ symbol in that line, which confused the Razor compiler. Check the documentation for a proper syntax rules.

  • Related