2017-08-09 34 views
0

我對其中包含以下工作的代碼<select>元件的正常工作標籤助手:TagHelperAttribute.Value是字符串類型,而不是鍵入ModelExpression,新型標籤

TagHelperAttribute forAttribute; 
if (!context.AllAttributes.TryGetAttribute("asp-for", out forAttribute)) 
{ 
    throw new Exception("No asp-for attribute found."); 
} 

var forInfo = (Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression)forAttribute.Value; 

我有相同的代碼在不同的標籤助手,我打電話給<date-picker>。在這第二個標籤幫手,投給ModelExpression失敗,因爲forAttribute.Value是,其實不是ModelExpression而是一個字符串(這是屬性名,「交貨期」,對此我想要的標籤綁定)。

看起來我的小說date-picker標記不知道asp-for值應該應用於Razor頁面模型。

如何確保我的date-picker收到正確的ModelExpression,以此爲基礎輸出?

回答

1

爲了確保您的屬性有正確的綁定,您需要在您的標記輔助類來定義一個屬性,與HtmlAttributeName屬性。例如:

[HtmlAttributeName("asp-for")] 
public ModelExpression For { get; set; } 

爲什麼需要屬性的原因是HtmlAttributeNameAttribute類做了很多幕後綁定正確的值。你可以看到價值是如何綁定在github上的。

此外,這簡化了您訪問屬性的值,因爲你並不需要經過整個列表。因此,而不是這樣的:

TagHelperAttribute forAttribute; 
if (!context.AllAttributes.TryGetAttribute("asp-for", out forAttribute)) 
{ 
    throw new Exception("No asp-for attribute found."); 
} 

var forInfo = (Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression)forAttribute.Value; 

你可以寫:

// you can call the For property 
var forInfo = For; 
相關問題