1

I have one ClassLibrary project in which I want to call a javascript function which should return some value.

How can I call a javascript function from my CS page in c#?

I search in google but not get perfect solution

2
  • Is this in the context of a .net application in .net 3.0, or is this in the context of I'm in a raw class library and want to interpret the JavaScript within this library? Commented May 15, 2014 at 21:24
  • stackoverflow.com/questions/5367946/… Commented May 19, 2014 at 2:15

3 Answers 3

0

How can I call a javascript function from my CS page in c#?

A class-library is basically a DLL that mostly encapsulates code and you can reference to from other class-libraries(DLLs) and use - The client code in your case would probably be an ASP.NET application DLL, I assume.

You can always call a JavasScript function from a C# / Class-Library using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","MyFunction()",true);

Just take on account that this code should be run in the context of a ASP.NET Page class in the event of the page is getting loaded (Page_Load).

In the case of a Class-Library, just make sure to have the right reference to it in your project (Right-Click on your project → Select Add Reference → Select and add your class-library).

Example code:

public void Page_Load(Object sender, EventArgs e)
{
    String csname1 = "PopupScript";
    String csname2 = "ButtonClickScript";
    Type cstype = this.GetType();

    ClientScriptManager cs = Page.ClientScript;

    if (!cs.IsStartupScriptRegistered(cstype, csname1))
    {
      String cstext1 = "alert('Hello World');";
      cs.RegisterStartupScript(cstype, csname1, cstext1, true);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can pass the Page reference to class Library and execute the JavaScript function inside the class library.

MyClassLib lib = new MyClassLib();
lib.RunJs(this.Page);

// In Class Lib 

Public Class MyClassLib 
{
  public void RunJs(System.Web.UI.Page page)
  {
      ClientScriptManager js = Page.ClientScript;
      ......
  }
}

I have not tried this please have a try on this.

Comments

0

You can call JavaScript Function from code behind using ScriptManager.RegisterStartupScript.

like:

JS Code:

function TestFunction() { 
       Alert("Test Function!!") 
       } 

Code Behind:

Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "TestFunction();", true);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.