You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor中Froala Editor事件绑定C#方法失败求助(IJSRuntime)

Blazor中实现Froala Editor事件调用C#方法

你遇到的Uncaught TypeError: l.opts.events[e].apply is not a function错误,根源是将事件处理函数以字符串形式传入Events字典,而Froala Editor期望的是JavaScript函数对象,而非字符串。以下是可行的解决方案:


步骤1:编写JS中间层处理函数

在wwwroot目录下创建或修改JS文件(比如froala-interop.js),定义专门的事件处理函数,用于桥接Froala事件和Blazor的C#方法:

// 存储组件引用(如果调用实例方法需要)
let blazorComponentRef;

// 注册组件引用(实例方法时使用)
window.registerFroalaComponentRef = function(ref) {
    blazorComponentRef = ref;
};

// Froala事件处理函数集合
window.froalaEventHandlers = {
    contentChanged: function() {
        // 调用静态方法
        return DotNet.invokeMethodAsync('PubbleCloud.Frontend.Client', 'PubbleCloud.Frontend.Client.Shared.Form.ContentChanged');
        
        // 如果是调用实例方法,替换为下面一行
        // return blazorComponentRef.invokeMethodAsync('ContentChanged');
    },
    click: function() {
        // 调用静态方法
        return DotNet.invokeMethodAsync('PubbleCloud.Frontend.Client', 'PubbleCloud.Frontend.Client.Shared.Form.Click');
        
        // 如果是调用实例方法,替换为下面一行
        // return blazorComponentRef.invokeMethodAsync('Click');
    }
};

// 包装Froala初始化方法,绑定事件
window.initFroalaWithEvents = function(selector, config) {
    // 为配置添加事件绑定
    config.events = {
        contentChanged: window.froalaEventHandlers.contentChanged,
        click: window.froalaEventHandlers.click
    };
    new FroalaEditor(selector, config);
};

步骤2:调整Blazor端代码

情况1:调用静态C#方法

直接调用包装后的JS初始化方法,无需额外处理组件引用:

var config = new FroalaEditorConfig()
{
    ToolbarInline = true,
    CharCounterCount = false,
    Key = KEY,
};
await JsRuntime.InvokeVoidAsync("initFroalaWithEvents", ".selector", config);

情况2:调用实例C#方法

需要先注册组件引用,再调用初始化方法:

[JSInvokable]
public void ContentChanged()
{
    Console.WriteLine("ContentChanged");
}

[JSInvokable]
public void Click()
{
    Console.WriteLine("Click");
}

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        // 注册组件引用到JS
        await JsRuntime.InvokeVoidAsync("registerFroalaComponentRef", DotNetObjectReference.Create(this));
        
        // 初始化Froala编辑器
        var config = new FroalaEditorConfig()
        {
            ToolbarInline = true,
            CharCounterCount = false,
            Key = KEY,
        };
        await JsRuntime.InvokeVoidAsync("initFroalaWithEvents", ".selector", config);
    }
}

关键注意事项

  • 确保C#方法上的[JSInvokable]特性没有遗漏,静态方法需要指定完整的命名空间+类名+方法名,实例方法只需方法名。
  • JS文件要在_Host.cshtml或index.html中正确引入,确保初始化时已加载。

内容的提问来源于stack exchange,提问作者Taco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 17:27:30