开发者

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 RegisterStartupScrip开发者_C百科t (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


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());
    }
  }


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜