Reputation: 361
function functionname1(arg1, arg2){content}
public string functionname(arg)
{
if (condition)
{
functionname1(arg1,arg2); // How do I call the JavaScript function from C#?
}
}
Please refer the above code and suggest me the idea to call a JavaScript function from C#.
Upvotes: 12
Views: 115122
Reputation:
You can call javascript functions from c# using Jering.Javascript.NodeJS, an open-source library by my organization:
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);
The library supports invoking directly from .js files as well. Say you have file C:/My/Directory/exampleModule.js
containing:
module.exports = (callback, message) => callback(null, message);
You can invoke the exported function:
string result = await StaticNodeJSService.InvokeFromFileAsync<string>("C:/My/Directory/exampleModule.js", args: new[] { "test" });
// result == "test"
Assert.Equal("test", result);
Upvotes: 1
Reputation: 1082
This may be helpful to you:
<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);
}
Upvotes: 8
Reputation: 2010
If you want to call JavaScript function in C#, this will help you:
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>");
}
}
Upvotes: 13
Reputation: 10931
<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);";
}
}
Upvotes: 3