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

时间:2016-01-18 23:14:56

标签: javascript c# jquery asp.net registerstartupscript

我已经研究并尝试了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);

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

  

脚本本身位于aspx中包含的javascript文件中   页面,我认为这可能是问题..但..我还没有找到任何   解决方法如何实际解决..

任何提示?

1 个答案:

答案 0 :(得分:2)

当您注册的脚本运行时,页面上没有JavaScript函数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); }

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

这是一个模板,请注意您检查脚本块是否已注册,以便在有回发后不会再次添加。

{ProductId: 123,
ProductName:'Widget',
Price:200.00,
minQuantity: 10,
Comments:[
    Price: "can be reduced blah blah",
    minQuantity: "N/A on orders > 1000"
]
}
相关问题