Call C# function from Javascript function

praveenuni
praveenuni used Ask the Experts™
on
Hello,

How to call a C# function (eg., main()) from a Javascript funtion (eg.,ref()).? On Button click I can use this statement :
document.getElementById("InBut").click(); But how can I call C# function without any clicks?

Regards
Praveen
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
you can use onMouseOver or any other javascript event to make a submit with all parameters you want

but you CAN'T call any C# function without submiting the page
and IMHO a page which submits itself without a click have a very bad usability....
Commented:
praveenuni,

Here is my code, already tested and run ok. When user click on ImageButton the program will alert 'hello' then alert 'dungla'.
=========== default.aspx===========
<%@ Page language="c#" Codebehind="default.aspx.cs" AutoEventWireup="false" Inherits="WebApp._default" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
     <HEAD>
          <title>default</title>
          <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
          <meta name="CODE_LANGUAGE" Content="C#">
          <meta name="vs_defaultClientScript" content="JavaScript">
          <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
          <script language="javascript">
          function init()
          {
               alert('hello ');
               <%SetData();%>;
               alert('<%=strName%>');
          }
          </script>
     </HEAD>
     <body MS_POSITIONING="GridLayout">
          <form id="Form1" method="post" runat="server">
               <asp:ImageButton id="ImageButton1" style="Z-INDEX: 103; LEFT: 312px; POSITION: absolute; TOP: 72px"
                    runat="server" ImageUrl="file:///C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\IDE\images\vb6tovb7.bmp"></asp:ImageButton>
          </form>
     </body>
</HTML>

=============== default.aspx.cs=========
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;

namespace WebApp
{
     /// <summary>
     /// Summary description for _default.
     /// </summary>
     public class _default : System.Web.UI.Page
     {
          public string strName = string.Empty;
          protected System.Web.UI.WebControls.ImageButton ImageButton1;
          private void Page_Load(object sender, System.EventArgs e)
          {
               if (!IsPostBack)
               {
                    this.ImageButton1.Attributes.Add("onclick", "javascript:init();");
               }
          }

          #region Web Form Designer generated code
          override protected void OnInit(EventArgs e)
          {
               //
               // CODEGEN: This call is required by the ASP.NET Web Form Designer.
               //
               InitializeComponent();
               base.OnInit(e);
          }
         
          /// <summary>
          /// Required method for Designer support - do not modify
          /// the contents of this method with the code editor.
          /// </summary>
          private void InitializeComponent()
          {    
               this.Load += new System.EventHandler(this.Page_Load);

          }
          #endregion

          public void SetData()
          {
               strName = "dungla";
          }
     }
}
if the C# function can be detouched from the page you are viewing
you can put it in another page and then onclick create an image whose source url
is on the page that when called runs your function

mypage.aspx
retunrs html with
<script language="JavaScript">
function report(param){
   var i=new Image();
   i.src='report.aspx&param=' + escape(param);
}
....  onclick="report('I am here');" ...
....  onclick="report('this and that');" ...
....  onclick="report('what ever');" ...

report.aspx
...
   AddToDB(Context.Request.QueryString.Get("param"));
...


I hope this helps
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Author

Commented:
in the above you are calling variable 'param' from the c# function. But I want to call the entire C# function from Javascript.

Author

Commented:
Hello,

The above code you posted is working just fine. But when I try to replciate the same in my code .. I'm getting errors.. Here is my code ..

Java Script function: (this will draw a rectangle on the imagebox of my aspx page)

function init()
{
        rect = null;
        ptr = null;

       MapImage = document.getElementById("MapImage");
       MapImage.onmousedown = setObj;
       MapImage.onmousemove = draw;

      xOffset = getX(MapImage);
      yOffset = getY(MapImage);
     document.onmouseup = clearObj;
     MapImage.ondragstart = function() {return false;};

     function setObj(e)
    {
        var sOffset = new Array(2);
         sOffset = getScrollOffset();
         rect = document.createElement("div");
         rect.className = "rectDraw";
         rect.onmousemove = showPos;
   
         sX = (window.event)? event.x: e.clientX;
         sY = (window.event)? event.y: e.clientY;
         sX -= (xOffset - sOffset[0]);
         sY -= (yOffset - sOffset[1]);

         rect.style.left = (sX+xOffset) + "px";
         rect.style.top = (sY+yOffset) + "px";

         document.body.appendChild(rect);
   }

  function clearObj()
  {
    if (rect)
    rect.parentNode.removeChild(rect);
    rect = null;
     <%SetData();%>; <------------------------- Assigned line
 
 }

  function draw(e)
  {
    if (rect)
    {
      var currX = (window.event)? event.x: e.clientX;
      var currY = (window.event)? event.y: e.clientY;

      // make sure not outside the bounds of image
      var leftX = getX(MapImage);
      var leftY = getY(MapImage);
      if (currX < leftX || currY < leftY)
        return false;

      var sOffset = new Array(2);
      sOffset = getScrollOffset();
      currX -= (xOffset - sOffset[0]);
      currY -= (yOffset - sOffset[1]);

      var diffX = currX - sX;
      var diffY = currY - sY;

      if (currX < sX)
      {
        rect.style.left = (currX+xOffset) + "px";
        diffX = Math.abs(diffX);
      }
      if (currY < sY)
      {
        rect.style.top = (currY+yOffset) + "px";
        diffY = Math.abs(diffY);
      }

      rect.style.width = diffX + "px";
      rect.style.height = diffY + "px";

      // output start & end coordinates
      document.getElementById("startX").value = (sX > currX)? currX: sX;
      document.getElementById("startY").value = (sY > currY)? currY: sY;
      document.getElementById("endX").value = (sX < currX)? currX: sX;
      document.getElementById("endY").value = (sY < currY)? currY: sY;
    }
  }

  function getX(obj)
  {
    var temp = obj;
    var left = 0;
    while (temp.offsetParent)
    {
      left += temp.offsetLeft;
      temp = temp.offsetParent;
    }
    return left;
  }

  function getY(obj)
  {
    var temp = obj;
    var top = 0;
    while (temp.offsetParent)
    {
      top += temp.offsetTop;
      temp = temp.offsetParent;
    }
    return top;
  }

  function getScrollOffset()
  {
    var x,y;
    if (self.pageYOffset) // all except Explorer
    {
      x = self.pageXOffset;
      y = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop)
    // Explorer 6 Strict
    {
      x = document.documentElement.scrollLeft;
      y = document.documentElement.scrollTop;
    }
    else if (document.body) // all other Explorers
    {
      x = document.body.scrollLeft;
      y = document.body.scrollTop;
    }
    var answer = new Array(x, y);
    return answer;
  }
}

and on the page_load event I assigned :


               if (!IsPostBack)
               {
                    this.ZoomInImgBut.Attributes.Add("onclick", "javascript:init();");
               }

and public void SetData()
{
}

when I try this, I'm unable to draw the rectangle on my image box. Could you please tell me whats wrong with my code..?
most visible problem is that the Init function is missing a }.

other then that, debugging that amount of code requires time,
it would help if you could say what exactly is the problem (what error do you get) ?
is there a public website where you are running this so I can see this in action or do i have to replicate the whole thing ?

Author

Commented:
This is the exact problem ..

I have a javascript function ( init() ) which will draw a rectangle on a image box of my asp.net page. This init() function should fire up only when I click a image button. While I'm drawing the rectangle and when I release the mouse (after I finish drawing the rectangle) -- there is a C# function SetData() which should get fired.

I'm sorry that, this is not on a public site for now. If you need any details or code, please let me know.

Thanks
Praveen

Author

Commented:
Init is the main function, which contains all the subfunctions like setobj, clearobj, draw.... I checked all the paranthesis and looks everything is ok. Could you please tell me where am I missing a }.

Commented:
You can try to add alert('here'); below the <%SetData();%>; line to debug

Author

Commented:
I tried alert('here'); statement, but still its showing there is a syntax error in the <%SetData();%>; line. I'm not getting the alert too.

-- Praveen

Commented:
Can you show us the code of SetData()? and please place alert('here') before you call SetData.
could it be that there is a redundent ; at the end of :
 <%SetData();%>;

when you get the error, can you please tell us exactly what it says and also
can you "view source" on the page that arrives at the client (as this error happens on the client side)
and tell us what exactly gets in place of the call above ?

Commented:
Hi,
I tried this solution. The trouble is that as <% %> are template elements, always they are called, independent that it is inside of a "if" (condition). So I tried the other way (.NET "calls" throught document.write, to JavaScript.
It is similar to have it "onload".
For use variables from the server side is great. It was useful

Regards

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial