Reputation: 1373
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?
Upvotes: 14
Views: 6994
Reputation: 11
@{
var htmlAttributes = (MyModel.MyCondition == true) ? (object)new
{
@@readonly = "readonly"
} : null;
}
@Html.TextBoxFor(m => m.Nom, htmlAttributes)
Upvotes: 0
Reputation: 431
What I do is create an @if statement. I find it more transparent.
@if (Model.MyCondition)
{
<input asp-for="Name" class="form-control" readonly="readonly" />
}
else
{
<input asp-for="Name" class="form-control" />
}
Upvotes: 0
Reputation: 10320
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 )" />
Upvotes: 17