I have custom component, in which having multiple events and each one have unique T type. Then JSInvokable method is common one (Entry point), from where i need to invoke the exact event functional handler.
While doing so, i need to convert the argument and Function handler in appropriate type. but due to type casting issue, i used dynamic type.
But am getting below issue in run time eventhough passed a proper argument type.
please check the error thrown screenshot:
Comp.razor
@using Typecasting
@using System.Threading.Tasks;
@using Newtonsoft.Json;
@inherits Base;
<input id="gencomp" type="text" />
@code {
[Parameter]
public EventCallback<ChangeEventArgs> ValueChange
{
get { return (EventCallback<ChangeEventArgs>)this.GetEvent("change"); }
set { this.SetEvent<ChangeEventArgs>("change", value); }
}
[Parameter]
public EventCallback<FocusOutEventArgs> FocusOut
{
get { return (EventCallback<FocusOutEventArgs>)this.GetEvent("blur"); }
set { this.SetEvent<FocusOutEventArgs>("blur", value); }
}
public async Task<string> DummyCall()
{
// dummy async action method to show case the issue
return await Task.Run(() => { return "data"; });
}
[JSInvokable]
// this is entry point
public override object Trigger(string eventName, string arg)
{
EventData data = this.DelegateList[eventName];
var eventarg = JsonConvert.DeserializeObject(arg, data.ArgumentType);
dynamic fn = data.Handler;
// here am getting the issue
fn.InvokeAsync(eventarg);
return eventarg;
}
}
base.cs
public Dictionary<string, EventData> DelegateList = new Dictionary<string, EventData>();
internal virtual void SetEvent<T>(string name, EventCallback<T> eventCallback)
{
if (this.DelegateList.ContainsKey(name))
{
this.DelegateList[name] = new EventData().Set<T>(eventCallback, typeof(T));
}
else
{
this.DelegateList.Add(name, new EventData().Set<T>(eventCallback, typeof(T)));
}
}
internal object GetEvent(string name)
{
if (this.DelegateList.ContainsKey(name) == false)
{
return null;
}
return this.DelegateList[name].Handler;
}
------
EventData class
public class EventData
{
public object Handler { get; set; }
public Type ArgumentType { get; set; }
public EventData Set<T>(EventCallback<T> action, Type type)
{
this.Handler = action;
this.ArgumentType = type;
return this;
}
}
you can find the issue reproducing sample from here.
https://github.com/gurunathancs1991/BlazorEventhandler
whether this is an issue with eventCallback conversion with dynamic type? any other work around for this?
change:
get { return (EventCallback<ChangeEventArgs>)this.GetEvent("change"); }
To:
get { return (EventCallback<ChangeEventArgs>)(object) this.GetEvent("change"); }
Perhaps now you don't need to use dynamic...
Good luck...
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.