简体   繁体   中英

Get property by dynamic key name?

I'm trying to avoid duplicating some templates, let's say I have the following (very simplified) template:

<div class="same-template">
    @(button?.buttonLeft.Url)
</div>
<div class="same-template">
    @(button?.buttonRight.Url)
</div>

I also have a button Right template as well, so my question is, is there a way I can pass in the "Side" of the button, and access the property? I know in javascript I'd do something like:

@(button?.button"+side+".Url) but obviously we're not using javascript.

I've tried creating a helper function

@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")

I hope this was clear enough!

EDIT: Ive made the following function, however on some it fails on the var b line with the following error:

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;
    }
}

C# is typed and doesn't provide functionalities like JavaScript. Anyway, you can try something like in follwoing example to dinamically read value of property by name:

<div>
    @(button?.GetType().GetProperty("PropertyNameWhichYouNeed").GetValue(button, null))
</div>

UPDATE:

Ok, I am think that you will need some extension method, but try first this:

button?.GetType().GetProperty("buttonRight").GetValue(button, null)
    .GetType().GetProperty("Url").GetValue(
button?.GetType().GetProperty("buttonRight").GetValue(button, null),
 null);

It became confusing :) I don't like this kind of UI but let try to explain:

Firs I retrieve type of buttonRight property. Then I retrieve type Url and supplied type of buttonRight instance.

It should be broken in following lines:

var buttonRight = button.GetType().GetProperty("buttonRight").GetValue(button, null);
var url = buttonRight.GetType().GetProperty("Url").GetValue(buttonRight, null);

Now url is value which you looking. Please see on fiddle how it works:

.NET Fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM