我是一個大菜鳥好了,請與我裸...通過動態密鑰名稱獲取屬性?
基本上,我試圖避免重複一些模板,比方說,我有以下的(非常簡化的)模板:
<div class="same-template">
@(button?.buttonLeft.Url)
</div>
<div class="same-template">
@(button?.buttonRight.Url)
</div>
我也有一個按鈕右邊的模板,所以我的問題是,有沒有一種方法,我可以通過按鈕的「一側」,並訪問該屬性?我知道在JavaScript我會做這樣的事情:
@(button?.button"+side+".Url)
但顯然我們沒有使用JavaScript。
我試圖創建一個輔助功能
@helper GetFooter(Object button, String side) {
<div class="same-template">
<!-- don't know what to do here... -->
@(button?.button<side>.Url)
</div>
}
@GetFooter(button, "Right")
我希望這是很清晰!
編輯: 香港專業教育學院做了以下功能,但在一些它與下面的錯誤var b
行失敗:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
@functions{
public dynamic GetNestedDynamicValue(IContentCardItem cardItem, String first, String second) {
var b = cardItem?.GetType().GetProperty(first).GetValue(cardItem, null);
var c = b?.GetType().GetProperty(second).GetValue(b, null);
return c;
}
}
那麼,你想要在頁面中呈現按鈕的屬性值?你想通過字符串名稱訪問該屬性? – kat1330
不支持您想要訪問該屬性的方式。你可以做的是檢查if子句中'side'的值,並根據該值使用按鈕的適當屬性。 –