Skip to content

Razor - no longer possible to add an HTML attribute using C# #18332

Closed
@razzemans

Description

@razzemans

Since .NET Core 3.x, it is no longer possible to have C# code in razor when an attribute declaration is expected. The following code used to work pre 3.x:

<option value="@someValue" @if(someCondition) { <text>selected</text> }>
    @displayText
</option>

In .NET Core 3.1, I get the following compilation error:

The tag helper 'option' must not have C# in the element's attribute declaration area.

Maybe it wasn't the most elegant code, but at least it was simple and worked well. I cannot think of a way to get something similar done in .NET Core 3.1. The only workaround I can think of is adding an if else statement and duplicating the HTML option tag, but that hardly seems like good practice. There are other common use cases where one might want to add a similar html attribute (checked, selected).

Either I am missing something utterly obvious or there should be some easy way to make this possible.

Further technical details

  • ASP.NET Core version 3.1
  • VS Enterprise 2019 16.4.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions