ScriptManager.RegisterStartupScript 在页面加载后在单独的 javascript 文件中触发 javascript 函数

ScriptManager.RegisterStartupScript to fire javascript function in seperate javascript file after Page Load

我已经研究并尝试了 3 种不同的解决方案,但一直无法克服烦人的错误:

Uncaught ReferenceError: SetupRichTextAndTags is not defined

情况:

我正在用数据填充隐藏域(C# 后端),这纯粹是 HTML,我将通过调用以下 javascript 来填充 SummerNote 富文本字段:

$(".summernote").code("your text");

我在 RegisterStartupScript 的尝试:

//ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", "$(function () { SetupRichTextAndTags(); });", true);
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "tmp", "<script type='text/javascript'>SetupRichTextAndTags();</script>", false);
ScriptManager.RegisterStartupScript(Page, GetType(), "SetupRichTextAndTags", "<script>SetupRichTextAndTags()</script>", false);

所有这些都给我错误...

The script itself is within an included javascript file in the aspx page, and i think that might be the issue.. But.. i have not found any solutions to how to actually fix that..

有什么建议吗?

JavaScript 功能 SetupRichTextAndTags 在您注册脚本 运行 时页面上不可用。

在调用该函数之前,您需要将其加载到页面中。您可以在客户端脚本块中声明该函数,但您必须将 JavaScript 写入 C# 代码,这不容易使用。相反,您可以在普通 JavaScript 文件中声明函数,然后将其加载到页面中。

这是一个模板,请注意您检查脚本块是否已注册,这样如果有 post 返回,它们就不会被再次添加。

ClientScriptManager csm = Page.ClientScript;

// this registers the include of the js file containing the function
if (!csm.IsClientScriptIncludeRegistered("SetupRichTextAndTags"))
{
    csm.RegisterClientScriptInclude("SetupRichTextAndTags", "/SetupRichTextAndTags.js");
}

// this registers the script which will call the function 
if (!csm.IsClientScriptBlockRegistered("CallSetupRichTextAndTags"))
{
    csm.RegisterClientScriptBlock(GetType(), "CallSetupRichTextAndTags", "SetupRichTextAndTags();", true);
}