'How to access C# class from Javascript

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?



Solution 1:[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.

Solution 2:[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.

Solution 3:[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
    }
 });

Solution 4:[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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nth
Solution 2 AaronS
Solution 3 Will Wang
Solution 4 MoonBoots89