We are experiencing the following error when build ASP.NET Core MVC application which is recently migrated from .NET Core 2.2 to 3.0:
The tag helper 'input' (or 'textarea' or any other) must not have C# in the element's attribute declaration area.
We used Razor @functions
to return HTML attribute content in order to overcome that issue but it looks ugly when you use variable for returning it from function without any extra logic (function dummy(htmlAttributeContent)
return htmlAttributeContent
)
@{
var roAttrHTML = "";
if (!user.GotAccessToken("someToken")) {
roAttrHTML = " readonly=\"readonly\" ";
}
}
<textarea class="testClass" asp-for="testId" @readonlyAttribute>@Model.Id</textarea>
Actually we got error
The tag helper 'textarea' must not have C# in the element's attribute declaration area.
when compile our ASP.NET Core MVC application whereas we need to get approach (better without @functions
usage) which will provide us a way to overcome that issue (as we have plenty of pages with similar logic which we need to touch once and avoid any possible problems with presumable new changes in support of attributes in the future .NET Core versions)
If you don't need to use the TagHelper, you can use <!elementName>
to disable it for a specific element:
<!textarea class="testClass" asp-for="testId" @readonlyAttribute>@Model.Id</!textarea>
See @glenn223's answer for a more structural solution. I made an improved version of his solution, by adding support for anonymous objects:
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace {YourBaseNameSpace}.Helpers.TagHelpers
{
[HtmlTargetElement(Attributes = "custom-attributes")]
public class CustomAttributesTagHelper : TagHelper
{
public object CustomAttributes { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var customAttributesDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(CustomAttributes);
foreach (var (key, value) in customAttributesDictionary)
{
output.Attributes.SetAttribute(key, value);
}
}
}
}
According to the docs, you can do it this way, in ASP .NET 5.0
<input asp-for="LastName"
disabled="@(Model?.LicenseId == null)" />
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-5.0#c-in-tag-helpers-attributedeclaration
You can do it like this:
@if (!user.GotAccessToken("someToken"))
{
<textarea class="testClass" asp-for="testId" readonly>@Model.Id</textarea>
}
else
{
<textarea class="testClass" asp-for="testId">@Model.Id</textarea>
}
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