C # method call in javascript function directly

How to call C # method in javascript function directly. (e.g. page_loadcode-by-page method). Please help me.

+3
source share
7 answers

To call the client side method, you need to do the following:

1- Create a server side method:

void DoSomething(...) { ... }

2- Embed System.Web.UI.IPostBackEventHandler.RaisePostBackEventthat takes one string argument (you can name the value of this argument) .:

public void RaisePostBackEvent(string eventArgument) 
{
        DoSomething(...);
}

3- Write a script to invoke the response entry:

function TriggerPostBack(control, arg){
    __doPostBack(control, arg);
}

4 If necessary, call the PostBack launch function:

<a .... onclick="TriggerPostBack('control', 'arg')" .. /> 
+2
source

You have several options, and each choice has its pros and cons.

  • page_Load, : window.location.reload() .
  • , XMLHttpRequest ( Ajax). jQuery Ajax.Net Professional ASP.NET Ajax.
+2

javascript , page_load . , . , ajax

0

: ( , page_load)! , , .

- AJAX! .

0

ASHX, #, , AJAX/jQuery, .

0

, , #, RPC (Remote ). , JSON-RPC.
-, json-, :

var request = {
    "method": "echo", 
    "params": ["Hello JSON-RPC"],
    "id": 1
}

, ,
, ,
id - .

. ajax. , , ajax, sendAjaxRequest, 3 :

  • script
  • sendAjaxRequest(scriptUrl,request,function(response){
        alert("the server responded with : "+response.result);
    });
    

, json-:

{
   "result": "Hello JSON-RPC", 
   "error": null, 
   "id": 1
}

.

, .

0

-, # JavaScript. . , .

ASP.NET. HTML- ASP.Net HTML.

<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
   onclick = "ShowCurrentTime()" />

JavaScript:. , ShowCurrentTime JavaScript, AJAX WebMethod GetCurrentTime. TextBox WebMethod.

<script type = "text/javascript">

function ShowCurrentTime() {
$.ajax({
    type: "POST",
    url: "CS.aspx/GetCurrentTime", //Type name of your class here e.g student.aspx/Method
    data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnSuccess,
    failure: function(response) {
        alert(response.d);
    }
});
}

function OnSuccess(response) {
    alert(response.d);
}

</script>

WebMethod. WebMethod . , (#), , jQuery AJAX .

#

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
    + DateTime.Now.ToString();
}
0

All Articles