How to access C# class from Javascript

2019-08-20 04:07发布

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?

4条回答
Summer. ? 凉城
2楼-- · 2019-08-20 04:28

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.

查看更多
相关推荐>>
3楼-- · 2019-08-20 04:39

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.

查看更多
Evening l夕情丶
4楼-- · 2019-08-20 04:42

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>
查看更多
叼着烟拽天下
5楼-- · 2019-08-20 04:45

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
    }
 });
查看更多
登录 后发表回答