vendredi 10 novembre 2023

.NET Core 7 Dynamic Component using reflection

I have one parent .razor component and one child and in the child I load a dynamic component with parameters.... all ok so far it loads and I can retrieve data from the DB. My issue is I need to call a method in the DynamicComponentFooter1 called "Update" when I click the update button.

Picture.razor (Parent)

<AMS.Resources.UI.Pages.Picture.Picture_Base @ref="Picture"
DynamicComponentFooter1="@DynamicComponentFooter1" DynamicComponentFooter1Parameters="@DynamicComponentFooter1Parameters" />

[Parameter] public Type? DynamicComponentFooter1 { get; set; }
[Parameter] public Dictionary<string, object>? DynamicComponentFooter1Parameters { get; set; }

Picture.razor.cs (I create the dynamic component called Picture_Membership)

this.DynamicComponentFooter1Parameters = new Dictionary<string, object>();

this.DynamicComponentFooter1Parameters.Add("UserCurrentClassName", "Picture_Membership");
this.DynamicComponentFooter1Parameters.Add("UserCurrentAction", "view");
this.DynamicComponentFooter1Parameters.Add("PictureID", "1");

this.DynamicComponentFooter1 = typeof(AMS.Resources.UI.Pages.Picture_Membership.Picture_Membership_Base);

Up till now all ok, but when i click the Update button in the parent I need to call the Update method in the dynamic control also either by reflection or any other way. The normal way would be to add a @ref="Picture_Membership" tag and call Picture_Membership.Update(); but I don't see a way I can add this as I am sending in the dynamic control.

Update Method is async Task:

public async Task<bool> Update()
{
    return true;
}

I dont see a way I can add a @ref tag so have tried the following:

var methodInfo = this.Picture.DynamicComponentFooter1.GetMethod("Update");

Type[] typeArgs = { typeof(Task<bool>) };
var genericMethodInfo = methodInfo.MakeGenericMethod(typeArgs);

var result = genericMethodInfo.Invoke(null, new object[]{});

But I get the following error:

An exception of type 'System.InvalidOperationException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'System.Threading.Tasks.Task`1[System.Boolean] Update() is not a GenericMethodDefinition. MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is true.'

enter image description here

What am I doing wrong?

Any help would be greatly appreciated :)





Aucun commentaire:

Enregistrer un commentaire