Reputation: 51
I am working with VS, a web form application, and I want to generate in the code-behind (C#) a JavaScript function defined in a JavaScript file in the project,. I have tried different ways ,such as this line of code:
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "Function_Name", true);
However, it can't resolve the name of my function since it's "not defined" as it's shown as a JavaScript error. But it works fine with a simple line of JavaScript code put in the Function_Name
field (like alert("something")
).
Any help with this please?
Upvotes: 1
Views: 1263
Reputation: 574
C#
define your javascript inside the C# code as text
Type type = this.GetType();
String key = "CallMyFunction";
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsClientScriptBlockRegistered(type, key))
{
StringBuilder script = new StringBuilder();
script.AppendLine("<script type=\"text/javascript\">");
script.AppendLine(" function Function_Name() {");
script.AppendLine(" frmMain.Message.value = 'Hello World';");
script.AppendLine(" }");
script.AppendLine("</script>");
cs.RegisterClientScriptBlock(type, key, script.ToString(), false);
}
or read your javascript from a .js file
<script type="text/javascript">
function Function_Name() {
frmMain.Message.value = 'Hello World';
}
</script>
Type type = this.GetType();
String key = "CallMyFunction";
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsClientScriptBlockRegistered(type, key) && File.Exists(path))
{
string script = File.ReadAllText(path);
cs.RegisterClientScriptBlock(type, key, script, false);
}
HTML - Body
<body>
<form id="frmMain" runat="server">
<input type="text" id="Message" />
<input type="button" value="Click!" onclick="Function_Name()" />
</form>
</body>
If you need a one-liner:
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "function Function_Name() { frmMain.Message.value='Hello World'; }", true);
or
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "<script type=\"text/javascript\">function Function_Name() { frmMain.Message.value='Hello World'; }</script>", false);
EDIT:
Using includes
String includeKey = "MyInclude";
String includeFile = "/myInclude.js";
String scriptKey = "CallMyFunction";
String script = "Function_Name();"; //Function inside your included js file.
Type type = GetType();
ClientScriptManager cs = Page.ClientScript;
//register the js file containing the function
if (!cs.IsClientScriptIncludeRegistered(includeKey))
{
cs.RegisterClientScriptInclude(includeKey, includeFile);
}
//register the script to call the function
if (!cs.IsClientScriptBlockRegistered(scriptKey))
{
cs.RegisterClientScriptBlock(type, scriptKey, script, true);
}
Upvotes: 1