在构建最近从 .NET Core 2.2 迁移到 3.0 的 ASP.NET Core MVC 应用程序时,我们遇到以下错误:
标签助手“input”(或“textarea”或任何其他)不得具有 C#
在元素的属性声明区域中。
我们用的是剃须刀@functions
返回 HTML 属性内容以克服该问题,但是当您使用变量从函数返回它而不需要任何额外的逻辑(函数dummy(htmlAttributeContent)
return htmlAttributeContent
)
@{
var roAttrHTML = "";
if (!user.GotAccessToken("someToken")) {
roAttrHTML = " readonly=\"readonly\" ";
}
}
<textarea class="testClass" asp-for="testId" @readonlyAttribute>@Model.Id</textarea>
实际上我们得到了错误
标签助手“textarea”元素的属性中不得包含 C#
申报区。
当编译我们的 ASP.NET Core MVC 应用程序时,我们需要获取方法(最好没有@functions
用法)这将为我们提供一种克服该问题的方法(因为我们有大量具有类似逻辑的页面,我们需要接触一次并避免在未来 .NET Core 版本中支持属性的可能的新更改中出现任何可能的问题)
如果不需要使用TagHelper,可以使用<!elementName>
对特定元素禁用它:
<!textarea class="testClass" asp-for="testId" @readonlyAttribute>@Model.Id</!textarea>
See @glenn223 的回答 https://stackoverflow.com/a/59579635/665825以获得更具结构性的解决方案。我通过添加对匿名对象的支持,对他的解决方案做了改进版本:
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);
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)