简体   繁体   English

Javascript:调用C#函数

[英]Javascript : call a C# function

firstly i have searched a lot and all topics seems to be C# : call or invoke a JavaScript function but i want to do the opposite , i want to create a function on C# and also on JavaScript and i want the JavaScript function call the C# function and retrieve it`s data , it seems like a good questions . 首先,我进行了大量搜索,所有主题似乎都是C#:调用或调用JavaScript函数,但是我想做相反的事情,我想在C#和JavaScript上创建一个函数,并且我希望JavaScript函数调用C#函数并检索它的数据,似乎是一个很好的问题。 The problem is that i have no knowledge on web and i do not know how does it work , but i tried a sample : 问题是我不了解网络,也不知道它是如何工作的,但是我尝试了一个示例:

Created a class : 创建了一个类:

public interface IFoo
{
    string Bar { get; set; }
}

public class Foo : IFoo
{
    public string Bar { get; set; }
}

Then 然后

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    public IFoo CreateFoo()
    {
        return new Foo() { Bar = "somevalue" };
    }

    public string Bar(IFoo foo)
    {
        return foo.Bar;
    }
}

And Javascript Code : 和Javascript代码:

<script type="text/javascript" language="javascript" >

function Callme(){
alert('Js function start . keep pressing OK')
var foo = external.CreateFoo();
alert(foo.Bar);
foo.Bar = "qwer";
alert(external.Bar(foo));
}
</script>

I get Error from the webbrowser control : 我从webbrowser控件中得到错误:

Error : "external" is null or not an object

But the javascript is not showing anything , please guide me if i missed something. 但是javascript没有显示任何内容,如果我错过了任何内容,请指导我。

Hold on guys. 等一下 PAUSE . 暂停 All of you need to slow down and read . 你们所有人都需要放慢速度并阅读 As this guy said: 就像这个家伙说的:

 I get Error from the webbrowser control :

Meaning he is embedding a webbrowser control that opens up this page which runs javascript. 表示他正在嵌入一个Web浏览器控件,该控件打开了运行javascript的页面。

To clear this up, I think he means that: 为了澄清这一点,我认为他的意思是:

  1. This is not online. 这不是在线的。
  2. He has a webBrowserControl in his C# application that opens up a page to run this javascript. 他的C#应用​​程序中有一个webBrowserControl,可打开一个页面来运行此javascript。
  3. In his app, he wants to use javascript to call a C# method from a class in his app. 在他的应用程序中,他想使用javascript从他的应用程序中的类调用C#方法。

Now, I agree that he was a bit ambiguous (hint, please be clearer with your question next time), but you guys are all posting answers and getting ahead of yourself. 现在,我同意他有点模棱两可 (提示,下一次请澄清您的问题),但是你们大家都在发布答案,超越自己。 In fact what he is describing is indeed possible, and this is how you do it. 实际上,他所描述的确实是可能的,而这就是您的方式。

Now the object you wanna reference in your javascript is window.external. 现在您要在javascript中引用的对象是window.external。 Here is an example in your javascript: 这是您的javascript中的示例:

window.external.CreateFoo(); 

to call CreateFoo(). 调用CreateFoo()。 However, before you can do so, you have to make your class visible to the page that your webbrowser is opening (window.external being the instanced class that you're referencing). 但是,在这样做之前,您必须使您的类对Web浏览器正在打开的页面可见(window.external是您所引用的实例化类)。

So, to set window.external, when you're creating webBrowser in C#: 因此,要在C#中创建webBrowser时设置window.external:

webBrowser1.ObjectForScripting = this;

So to sum it up: 总结一下:

  1. In your C# app, set ObjectForScripting of your web browser control to whatever object you want to reference in Javascript. 在C#应用程序中,将Web浏览器控件的ObjectForScripting设置为要在Javascript中引用的任何对象。
  2. In the Javascript on your page, you can call window.external.YOURMETHOD(); 在页面上的Javascript中,您可以调用window.external.YOURMETHOD(); to call any public method from that ObjectForScripting class that you set originally. 从您最初设置的ObjectForScripting类中调用任何公共方法。

I hope this helps your situation and others will be a bit more careful when reading your question. 希望这对您有帮助,其他人在阅读问题时会更加谨慎。

EDIT: Also as a reminder, the webBrowserControl depends on the version on IE that the user has installed on his/her computer. 编辑:还要提醒一下,webBrowserControl取决于用户已在他/她的计算机上安装的IE版本。 So be careful on versioning, javascript will only perform to the extent of what his/her version of IE can handle (same goes for styling and etc.) 因此,在版本控制上要格外小心,javascript只会在其版本的IE可以处理的范围内发挥作用(样式等也是如此)。

Edit Edit: You also need to add the ComVisible attribute [ComVisible(true)] 编辑编辑:您还需要添加ComVisible属性[ComVisible(true)]

there is some misunderstood here. 这里有些误会。

Javascript can't call server function. Javascript无法调用服务器功能。

Use Ajax for that. 为此使用Ajax。

The only way we can think about that is in a framework like GWT, but be careful : GWT compile your java code in javascript which calls via ajax the server. 我们可以考虑的唯一方法是在GWT之类的框架中,但要小心:GWT在javascript中编译Java代码,而javascript是通过ajax服务器调用的。

The thing to have in memory is that if a framework propose you to call a C# or java method directly in javascript, it does not really perform that : it calls a server resource using ajax and then the server resource call the method. 内存中存在的问题是,如果框架建议您直接使用javascript调用C#或java方法,则它实际上并不会执行该操作:它使用ajax调用服务器资源,然后服务器资源调用该方法。 The method returns and the ajax response is sent to javascript. 该方法返回,并且ajax响应发送到javascript。

You should really look into how HTTP works and then re-evaluate your question. 您应该真正研究HTTP的工作原理,然后重新评估您的问题。

You simply can't call a C# function directly from JavaScript because your JavaScript is executed on the client by the browser while the C# is run on the server by the Web server. 您根本无法直接从JavaScript调用C#函数,因为您的JavaScript是由浏览器在客户端上执行的,而C#是由Web服务器在服务器上运行的。

If you want to call a function on the server you need to do that through a AJAX request using some kind of Web library like ASP.NET WebAPI or ASP.NET MVC. 如果要在服务器上调用函数,则需要使用某种Web库(例如ASP.NET WebAPI或ASP.NET MVC)通过AJAX请求来实现。

To explain Jerome C's answer slightly further. 为了进一步解释Jerome C的答案。

C# is a server-side language which is executed by a server request. C#是由服务器请求执行的服务器语言。 Whereas JavaScript is client-side language, meaning it is handled by the browser. JavaScript是客户端语言,这意味着它是由浏览器处理的。 Both have their advantages, and both are commonly used for the same thing, such as validation. 两者都有自己的优势,并且通常用于同一事物,例如验证。 The server-side language is a secure way of ensuring something, or executing a command between a database for example. 服务器端语言是确保某些内容或在数据库之间执行命令的安全方式。 Whereas the client-side language (JavaScript), is more commonly used to improve the user experience but making things more interactive. 客户端语言(JavaScript)更常用于改善用户体验,但使事情更具交互性。

As people have suggested, there are ways to communicate between the two, but not "directly". 正如人们所建议的那样,有两种方法可以在两者之间进行通信,但不能“直接”进行通信。 The key word here is AJAX. 这里的关键词是AJAX。 Using an open source library such as jQuery http://jquery.com/ on the client-side, and then a custom handler (.ASHX file) on the server-side, you can make asynchronous requests between the client and the server. 使用客户端上的jQuery http://jquery.com/等开源库,然后在服务器端上使用自定义处理程序(.ASHX文件),可以在客户端和服务器之间发出异步请求。

On a slightly more advanced note; 稍稍先进一点; you can directly communicate between JavaScript and C# objects using a library such as SignalR https://github.com/SignalR/SignalR it's a tiny bit fiddly to setup, so I wouldn't recommend it for this instance, but it would definitely be something to consider in the future. 可以使用诸如SignalR https://github.com/SignalR/SignalR之类的库直接在JavaScript和C#对象之间进行通信,这有点麻烦,所以我不建议在此实例中使用它,但是绝对可以将来要考虑的事情。

You can't call server function by Javascript directly. 您不能直接使用Javascript调用服务器功能。

If you need , you can use the __doPostBack("Button1","") instead. 如果需要,可以改用__doPostBack("Button1","")

Put your action in the Button1's event. 将您的操作放入Button1的事件中。

Javascript and serverside languages cannot directly talk to each other. Javascript和服务器端语言无法直接相互交流。

The most common (I think) way to do this is using some sort of Ajax call a serverside Web Service: 我认为最常见的方法是使用某种Ajax调用服务器端Web服务:

This means you make a special call in javascript that will reach to a class method written in C#. 这意味着您使用javascript进行了特殊调用,该调用将到达用C#编写的类方法。

Before reading about and making Ajax calls, you should read up on HTTP protocol and how communication between web server and browsers is executed. 在阅读和进行Ajax调用之前,您应该阅读HTTP协议,以及如何执行Web服务器与浏览器之间的通信。 I think the article in this link is a good place to start reading about HTTP. 我认为此链接中的文章是开始阅读有关HTTP的好地方。

You can read about WebServices Web Services related Wiki article , and about Ajax in Ajax wiki Article . 您可以在Ajax Wiki文章中阅读有关WebServices Web Services的相关Wiki文章 ,以及有关Ajax的信息

Also : 另外:

  • Ajax calls do not have to be written by hand, javascript frameworks like jQuery can be used. Ajax调用不必手工编写,可以使用jQuery之类的javascript框架。 (in jQuery a function like jQuery.$ajax() is very usefull in making ajax calls ) (在jQuery中,像jQuery。$ ajax()这样的函数在进行ajax调用时非常有用)
  • There is an alternative way to do this - you can use a page method . 有另一种方法可以执行此操作-您可以使用页面方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM