First, if you haven't already done so, you will need the following using statements in your code in order to use the HtmlPage class.
using System.Windows.Browser;Now, we can get started on calling JavaScript from C# using dynamic. We need to access the underlying HTML page that contains our JavaScript code, so we will use the HtmlPage class to do so and assign it to a dynamic variable.
dynamic htmlWindow = HtmlPage.Window;Now we can invoke JavaScript methods on the page using the htmlWindow variable and receive return values as well. To do this, we simply call the JavaScript function as we would call a function that is in a class.
dynamic sum = htmlWindow.addWithJavaScript(10, 13);The JavaScript function is as follows
function addWithJavaScript(var1, var2)
{
var sum = var1 + var2;
alert("JS sum: " + sum);
return sum;
}Together, the C# code is very concise and only takes two lines to communicate with JavaScript
dynamic htmlDocument = HtmlPage.Window;
dynamic sum = htmlDocument.addWithJavaScript(10, 13);
MessageBox.Show("C# return value: " + sum); // Just to show the results in C#
For more information on the dynamic keyword in C# and the DLRhttp://msdn.microsoft.com/en-us/library/dd264741.aspx (C# Dynamic)
http://msdn.microsoft.com/en-us/library/dd233052.aspx (DLR)
No comments:
Post a Comment