user517406
user517406

Reputation: 13773

calling javascript from c#

I need to use the javascript functions to show and hide an element on my page, but calling it from within a C# method. Is this possible?

EDIT : I tried RegisterStartupScript (see below) but this did not hide the elements as I had hoped :

HidePopup("CompanyHQSetup", "$('#<%=DivDataProvider.ClientID %>').hide();$('#<%=modalOverlay.ClientID %>').hide();");

private void HidePopup(string Key, string jscript)
    {
        string str = "";
        str += "<script language='javascript'>";
        str += jscript;
        str += "</script>";
        RegisterStartupScript(Key, jscript);
    }

EDIT : Got around this by using a hidden field boolean to determine whether or not to hide or show the elements

Upvotes: 1

Views: 3662

Answers (4)

Devjosh
Devjosh

Reputation: 6496

you can use page.RegisterClientScript method to do that go on the following url http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerclientscriptblock.aspx

and give it a try

Upvotes: 1

Mihai Oprea
Mihai Oprea

Reputation: 2047

Javascript is client side, c# is server side. You can't call javascript directly from C#. Take a look at Comet though, it will show you how you can push data from the HTTP server to the webpage.

Upvotes: 0

Tom Gullen
Tom Gullen

Reputation: 61729

One is server side, the other is client side. They can pass variables to each other (Javascript to ASP would be via forms/querystring/cookies and ASP to JS done via response.writing variables), but they can't directly interact.

Upvotes: 1

dcp
dcp

Reputation: 55424

Yes, check out RegisterClientScriptBlock.

Here's a snippet taken from that link:

  public void Page_Load(Object sender, EventArgs e)
  {
    // Define the name and type of the client script on the page.
    String csName = "ButtonClickScript";
    Type csType = this.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Check to see if the client script is already registered.
    if (!cs.IsClientScriptBlockRegistered(csType, csName))
    {
      StringBuilder csText = new StringBuilder();
      csText.Append("<script type=\"text/javascript\"> function DoClick() {");
      csText.Append("Form1.Message.value='Text from client script.'} </");
      csText.Append("script>");
      cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
    }
  }

Upvotes: 5

Related Questions