Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Razor: Conditional attribute without value

I want to conditionally render a readonly attribute in an <input>. In the ASP.NET Core dialect of Razor the interpretation of attributes is a little different opposed to System.Web.Mvc.

In System.Web.Mvc I used to do:

<input name="Name" class="form-control" @(Model.MyCondition ? "readonly" : "") />

In ASP.NET Core, the same does not work: no error, but the attribute isn't rendered either.

<input asp-for="Name" class="form-control" @(Model.MyCondition ? "readonly" : "" ) />

Once the attribute is present in the HTML it is enforced, so I cannot do something with the value of the attribute. This snippet would cause the input to always be read-only:

<input asp-for="Name" class="form-control" readonly="@(Model.MyCondition ? "readonly" : "" )" />

Now, I can work around by creating a tag helper that would respond to the is-readonly tag, but that seems very convoluted for something so simple.

How do I conditionally render a no-value attribute without resorting to a custom tag helper?

like image 238
Sebazzz Avatar asked Apr 24 '19 19:04

Sebazzz


1 Answers

If you set the value to null when your condition isn't matched (instead of an empty string) then the attribute will not be rendered, as follows:

<input asp-for="Name" class="form-control" readonly="@(Model.MyCondition ? "readonly" : null )" />
like image 53
SpruceMoose Avatar answered Sep 22 '22 01:09

SpruceMoose