gpt4 book ai didi

JavaScript 函数未在 C# 代码中定义

转载 作者:行者123 更新时间:2023-11-30 19:20:49 25 4
gpt4 key购买 nike

我正在使用 VS,一个 Web 表单应用程序,我想在代码隐藏 (C#) 中生成一个在项目的 JavaScript 文件中定义的 JavaScript 函数。我尝试了不同的方法,例如这行代码:

Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "Function_Name", true);

但是,它无法解析我的函数名称,因为它“未定义”,显示为 JavaScript 错误。但是在 Function_Name 字段(如 alert("something"))中放入一行简单的 JavaScript 代码就可以正常工作。

请问有什么帮助吗?

最佳答案

C#

将 C# 代码中的 javascript 定义为文本

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

或者从 .js 文件中读取你的 javascript

<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>
<form id="frmMain" runat="server">
<input type="text" id="Message" />
<input type="button" value="Click!" onclick="Function_Name()" />
</form>
</body>

如果您需要单线:

Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "function Function_Name() { frmMain.Message.value='Hello World'; }", true);

Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "<script type=\"text/javascript\">function Function_Name() { frmMain.Message.value='Hello World'; }</script>", false);

编辑:

使用包含

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

关于JavaScript 函数未在 C# 代码中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57506334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com