function functionname1(arg1, arg2){content}
public string functionname(arg)
{
if (condition)
{
functionname1(arg1,arg2); // How do I call the JavaScript function from C#?
}
}
请参考上面的代码并建议我从C#调用JavaScript函数。
答案 0 :(得分:11)
如果您想在C#中调用JavaScript函数,这将对您有所帮助:
public string functionname(arg)
{
if (condition)
{
Page page = HttpContext.Current.CurrentHandler as Page;
page.ClientScript.RegisterStartupScript(
typeof(Page),
"Test",
"<script type='text/javascript'>functionname1(" + arg1 + ",'" + arg2 + "');</script>");
}
}
答案 1 :(得分:8)
这可能对您有所帮助:
<script type="text/javascript">
function Showalert() {
alert('Profile not parsed!!');
window.parent.parent.parent.location.reload();
}
function ImportingDone() {
alert('Importing done successfull.!');
window.parent.parent.parent.location.reload();
}
</script>
if (SelectedRowCount == 0)
{
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "importingdone", "ImportingDone();", true);
}
答案 2 :(得分:2)
<head>
<script type="text/javascript">
<%=YourScript %>
function functionname1(arg1,arg2){content}
</script>
</head>
public string YourScript = "";
public string functionname(arg)
{
if (condition)
{
YourScript = "functionname1(arg1,arg2);";
}
}
答案 3 :(得分:1)
作为替代方案,您始终可以使用SignalR在服务器端C#代码和客户端JavaScript代码之间来回通信。
答案 4 :(得分:1)
您可以使用Jering.Javascript.NodeJS(我组织的开放源代码库)从c#调用javascript函数:
string javascriptModule = @"
module.exports = (callback, x, y) => { // Module must export a function that takes a callback as its first parameter
var result = x + y; // Your javascript logic
callback(null /* If an error occurred, provide an error object or message */, result); // Call the callback when you're done.
}";
// Invoke javascript
int result = await StaticNodeJSService.InvokeFromStringAsync<int>(javascriptModule, args: new object[] { 3, 5 });
// result == 8
Assert.Equal(8, result);
该库还支持直接从.js文件调用。假设您的文件C:/My/Directory/exampleModule.js
包含:
module.exports = (callback, message) => callback(null, message);
您可以调用导出的函数:
string result = await StaticNodeJSService.InvokeFromFileAsync<string>("C:/My/Directory/exampleModule.js", args: new[] { "test" });
// result == "test"
Assert.Equal("test", result);