How to access C# class from Javascript

2019-08-20 03:53发布

问题:

I have a class named book in C#. In an ASPX page (which has access to book class), I have an iframe element. I want to use Javascript from the page in the iframe, to call book.write(), but I'm not sure if I can call a C# method from a page inside an iframe using Javascript.

How I can do that?

回答1:

You will have to make postback using javascript to the server with some parameters and then the server side can access the required class and function as per the parameter.



回答2:

c# = server side, JavaScript = client side. You cannot directly interact with one from the other.

The best you can do is to have some sort of postback, (through a button click, or other method) which would then call the method in your book class.

To execute JavaScript code from c#, you need to write a JavaScript call in your rendered page, from a post back.



回答3:

Try AJAX,in your aspx.cs file,add this

 [WebMethod]
public static string CallCSharpCode(){
    new book().write();
}

use AJAX call the method,

 $.ajax({
    type : "POST",
    contentType : "application/json; charset=utf-8",
    url : "your aspx page.aspx/CallCSharpCode",
    dataType : "json",
    success : function (data) {
        var obj = data.d;
        //your code
    },
    error : function (result) {
        //your code
    }
 });


回答4:

There's no way you can access a C# class by using JavaScript - Never, you can't do it. All you can do is use <% ... %> and then call your class method through that.

Here's an example:

Your class has a method LIKE this (note that you must declare the method as public to access it on your page):

public String Hello()
{
    return "Hello!";
}

And then you want to diplay it in your ASPX page by this:

<body>
    <form id="form1" runat="server">
        <input type="button" value="Test" onclick="alert('<%= Hello() %>')" />
    </form>
</body>