[英]ASP.NET Core -> Label asp-for not returning label text
[英]ASP.NET Core 6, Obtaining Metadata for a custom asp-for TagHelper in the context of an EditorTemplate
在 ASP.NET Core 6 的常規 razor 視圖中給定一個語句編輯器。
@Html.EditorFor(_ => _.Person.FirstName, "boot-text")
model 看起來像這樣。
public class Model
{
[DataMember(Name = "firstName", IsRequired = true)]
[Required]
[StringLength(250)]
[DataType(DataType.Text)]
[DisplayName("Given Name")]
public string? FirstName { get; set; }
}
我創建了一個自定義模板。 boot-text.cshtml
<div class="row mb-15px">
<label asp-for="@Model" class="form-label col-form-label col-md-3"></label>
<div class="col-md-9">
<input asp-for="@Model" type="text" class="form-control mb-5px"
<span asp-validation-for="@Model"></span>
</div>
</div>
我有一個標簽助手。
[HtmlTargetElement("input", TagStructure = TagStructure.Unspecified)]
public class AspForTagHelper : TagHelper
{
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
// For is null here
}
}
在上面的TagHelper
中,model 總是NULL。
我在這里查看了源代碼: https://github.com/do.net/as.netcore/blob/main/src/Mvc/Mvc.TagHelpers/src/InputTagHelper.cs
我將所有源代碼復制到我自己的標簽助手中,並且在For.Metadata
處也得到了引用異常
var metadata = For.Metadata;
var modelExplorer = For.ModelExplorer;
這就引出了一個問題,默認標簽助手如何設法獲取 model 元數據。 如果我只是完全刪除我的標簽助手,上面的 asp-for 渲染就可以很好地使用我的模板。
所以我找到的源代碼可能不是真正的 AS.NET Core 6 源代碼?
您的標簽助手將根據[HtmlTargetElement]
屬性的內容運行。
當您的標簽助手運行時,您的屬性將根據任何[HtmlAttributeName]
進行綁定。 但是這個綁定是可選的,不會阻止你的標簽助手運行。
由於您只指定了[HtmlTargetElement("input"
並且沒有包含任何必需的Attributes =
,因此您的標簽助手將針對所有<input
標簽運行,即使它們沒有asp-for
屬性。這解釋了為什么您會看到您的For
財產總是null
。
TLDR:你需要的是;
[HtmlTargetElement("input", Attributes = "asp-for", TagStructure = TagStructure.Unspecified)]
public class AspForTagHelper : TagHelper
{ ... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.