简体   繁体   中英

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

I have studied and tried 3 different solutions, but haven't been able to get past the annoying error :

Uncaught ReferenceError: SetupRichTextAndTags is not defined

Situation :

I am populating a hiddenfield with data (C# back-end), this is purely HTML which i will use to populate a SummerNote rich-text field by calling the following javascript :

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

My tries at 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);

All of these gives me the error...

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..

Any tips ?

The JavaScript function SetupRichTextAndTags is not available on the page when your registered scripts run.

Before you can call the function you need to load it into the page. You can declare the function in a client script block but then you have to write the JavaScript into the C# code which is not easy to work with. Instead you can declare the functions in a normal JavaScript file and then load that into the page.

Here is a template, note that you check if the script blocks are registered so they don't get added again if there is a post back.

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);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM