Skip to content Skip to sidebar Skip to footer

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.writ

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

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:

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

 [WebMethod]
publicstaticstringCallCSharpCode(){
    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:

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><formid="form1"runat="server"><inputtype="button"value="Test"onclick="alert('<%= Hello() %>')" /></form></body>

Post a Comment for "How To Access C# Class From Javascript"