Chazz1 Chazz1 - 7 months ago 18
Javascript Question

Calling C# function through Javascript (without Json)

I have a function named "callfunction()" in JavaScript(Mypage.aspx) .This function should call another function "func()" in C# (Mypage.aspx.cs )

Something like this:

(in Mypage.aspx)


function callfunction()

{

// i have to call func() function here .....

}

</script>


(in Mypage.aspx.cs file)

public void func()

{

// My code goes here

}


I have researched alot because of this and i ended up so far with 2 conclusions:
1st was to use Json, but my superiors said clearly that they dont want me to do so.
2nd was that i cant do as i wish because of the client, server aspnet protocol

Please give me any kind of tip in how to do this, i am getting desperate

Answer

If it's a webforms project (not MVC) and you don't want to use AJAX, you can use __doPostBack.

<script type="text/javascript">
 function callfunction(parameter)
 {
     __doPostBack('func', parameter)
 }
</script>

C#:

public void Page_Load(object sender, EventArgs e)
{
  string parameter = Request["__EVENTARGUMENT"]; // parameter
  var senderObject = Request["__EVENTTARGET"]; // func
  if(senderObject == "func")
  {
     //call your function here, or write the implementation
  }
}