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?
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 )" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With