簡體   English   中英

從 C# 調用 JavaScript 函數

[英]Call JavaScript function from C#

Javascript.js

function functionname1(arg1, arg2){content}

C#文件

public string functionname(arg)
{
    if (condition)
    {
        functionname1(arg1,arg2); // How do I call the JavaScript function from C#?
    }
}

請參考上面的代碼並建議我從 C# 調用 JavaScript 函數的想法。

如果你想在 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>");
    }
}

這可能對您有幫助:

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

標題部分中的 .aspx 文件

<head>
    <script type="text/javascript">
        <%=YourScript %>
        function functionname1(arg1,arg2){content}
    </script>
</head>

.cs 文件

public string YourScript = "";
public string functionname(arg)
{
    if (condition)
    {
        YourScript = "functionname1(arg1,arg2);";
    }
}

作為替代方案,您始終可以使用SignalR在服務器端C#代碼和客戶端JavaScript代碼之間來回通信。

您可以使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM