Page 1 of 1
javascript How to call c # method
Posted: Sun Jan 22, 2017 10:11 pm
by tomny
Dear JS-Support,
javascript function How to call c# code (method or property)?
Thank you.
Regards,
Tomny
Re: javascript How to call c # method
Posted: Mon Jan 23, 2017 2:49 am
by JS-Support @Userware
Hi,
Here is how to call C# from JavaScript:
Code: Select all
void Test()
{
CSHTML5.Interop.ExecuteJavaScript(@"
// This is JavaScript code
alert('Hello from JavaScript');
// Let's call the C# method "MyCSharpMethod". Due to the fact that it is passed as the first parameter to this ExecuteJavaScript call, we can access it with $0:
$0();
", (Action)MyCSharpMethod);
}
void MyCSharpMethod()
{
System.Windows.MessageBox.Show("Hello from C#");
}
For reference, here is a link to the documentation page "How to Call JavaScript from C#":
http://cshtml5.com/links/how-to-call-javascript.aspxRegards,
JS-Support
Re: javascript How to call c # method
Posted: Mon Jan 23, 2017 8:39 am
by tomny
Hi,
thank you for your reply. I now seek is the direct implementation of js c # method, not through
CSHTML5.Interop.ExecuteJavaScript ("$0()", (Action)MyCSharpMethod).
I tried: CSHTML5.Interop.ExecuteJavaScript ("var Method1 = $0", (Action)MyCSharpMethod),
and then in the implementation of js call Method1(). Also strangely, the simulator runs successfully, but the browser fails on the prompt
Re: javascript How to call c # method
Posted: Tue Jan 24, 2017 3:02 am
by JS-Support @Userware
Hi,
Oh, I see, you want to make the C# method globally accessible from any JS code. To do that, you can add the method to the browser "window" object for example, like this:
Code: Select all
CSHTML5.Interop.ExecuteJavaScript ("window.method1 = $0", (Action)MyCSharpMethod);
It should work both in the browser and in the Simulator.
Regards,
JS-Support
Re: javascript How to call c # method
Posted: Tue Jan 24, 2017 10:08 pm
by tomny
Dear JS-Support,
Thank you, the code can work. This function is useful, and sometimes when we call a js method, you need to let js automatically return to the c # method, you can achieve this.
Regards,
Tomny
Re: javascript How to call c # method
Posted: Tue Jul 18, 2017 12:17 pm
by kmatt
I have the following C# code:
Interop.ExecuteJavaScript(@"window.method1 = $0;method1();",(Action)Dummy);
public void Dummy()
{
Debug.WriteLine("Called dummy");
}
Dummy is never called. I've also tried making the method static but it still doesn't work. Has something changed?
Re: javascript How to call c # method
Posted: Sat Aug 19, 2017 6:44 am
by JS-Support @Userware
Hi,
Please find attached a project that works properly on my machine.
Let me know if you see any differences.
Thanks.
Regards,
JS-Support