如何从客户端JavaScript函数调用服务器方法背后的代码?

时间:2022-06-12 15:30:37

I am having an JavaScript function for a HTML button click event in ASPX page. And a server Method in its code behind page. Now i want to call the server method from the JavaScript function with some parameters only when the HTML button is clicked by the user.

我在ASPX页面中有一个HTML按钮单击事件的JavaScript函数。和一个服务器方法在它的代码页后面。现在,我想从JavaScript函数中调用服务器方法,只有当用户单击HTML按钮时才使用一些参数。

Please don't change this scenario and also don't use any asp.net contols in the aspx page while replying. Because only HTML controls are allowed. Can anyone help me on this ?. Thanks in advance. Eagerly waiting for answers.

请不要更改此场景,也不要在回复时在aspx页面中使用任何asp.net内容。因为只允许HTML控件。在这件事上谁能帮我一个忙吗?提前谢谢。急切地等待答案。

Here is the code,

这是代码,

Code in markup:

在标记的代码:

<script language="javascript" type="text/javascript">
    function btnAccept_onclick() {        
        var name;            
        name = document.getElementById('txtName').value;

        // Call Server side method SetName() by passing this parameter 'name'
</script>

<input type="button" id="btnAccept" value="Accept" onclick="return btnAccept_onclick()" />

Code-behind:

后台代码:

public void SetName(string name)
{
    // Code for some functionality    
}

9 个解决方案

#1


36  

Yes, you can make a web method like..

是的,你可以制作一个像…

[WebMethod]
public static String SetName(string name)
{
    return "Your String"
}

And then call it in JavaScript like,

然后用JavaScript,

PageMethods.SetName(parameterValueIfAny, onSuccessMethod,onFailMethod);

This is also required :

这也是必须的:

<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>

#2


22  

In my projects, we usually call server side method like this:

在我的项目中,我们通常调用服务器端方法如下:

in JavaScript:

在JavaScript中:

document.getElementById("UploadButton").click();

Server side control:

服务器端控制:

<asp:Button runat="server" ID="UploadButton" Text="" style="display:none;" OnClick="UploadButton_Click" />

C#:

c#:

protected void Upload_Click(object sender, EventArgs e)
{

}

#3


6  

If you dont want to use ajax than

如果您不想使用ajax,请使用

Code behind 

void myBtn_Click(Object sender,EventArgs e)
{
   //SetName(name); your code
}


.aspx file

<script language="javascript" type="text/javascript">
    function btnAccept_onclick() {        
        var name;            
        name = document.getElementById('txtName').value;
        document.getElementById('callserver').click();
        // Call Server side method SetName() by passing this parameter 'name'
</script>


<div style="dispaly:none;">
  <input type="button" id="callserver" value="Accept" click="myBtn_Click" runat="server" />
</div>
<input type="button" id="btnAccept" value="Accept" onclick="return btnAccept_onclick()" />

or use page method

或使用页面的方法

.cs file
[ScriptMethod, WebMethod]

   public static string docall()
   {
      return "Hello";
   }

.aspx file

<script type="text/javascript">
      function btnAccept_onclic() {
          PageMethods.docall(onSuccess, onFailure);
      }

  function onSuccess(result) {
          alert(result);
      }


      function onFailure(error) {
          alert(error);
      } 

</script>

check this : http://blogs.microsoft.co.il/blogs/gilf/archive/2008/10/04/asp-net-ajax-pagemethods.aspx

检查:http://blogs.microsoft.co.il/blogs/gilf/archive/2008/10/04/asp-net-ajax-pagemethods.aspx

#4


1  

Ajax is the way to go. The easiest (and probably the best) approach is jQuery ajax()

使用Ajax是正确的。最简单(可能也是最好的)方法是jQuery ajax()

You'll end up writing something like this:

你最终会写这样的东西:

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    // do something when done
  }
});

#5


1  

I had to register my buttonid as a postbacktrigger...

我必须将我的buttonid注册为postbacktrigger。

RegisterPostbackTrigger(idOfButton)

#6


1  

// include jquery.js
//javascript function
var a1="aaa";
var b1="bbb";
                         **pagename/methodname**     *parameters*
CallServerFunction("Default.aspx/FunPubGetTasks", "{a:'" + a1+ "',b:'" + b1+ "'}",
            function(result)
            {

            }
);
function CallServerFunction(StrPriUrl,ObjPriData,CallBackFunction)
 {

    $.ajax({
        type: "post",
        url: StrPriUrl,
        contentType: "application/json; charset=utf-8",
        data: ObjPriData,
        dataType: "json",
        success: function(result) 
        {
            if(CallBackFunction!=null && typeof CallBackFunction !='undefined')
            {
                CallBackFunction(result);
            }

        },
        error: function(result) 
        {
            alert('error occured');
            alert(result.responseText);
            window.location.href="FrmError.aspx?Exception="+result.responseText;
        },
        async: true
    });
 }

//page name is Default.aspx & FunPubGetTasks method
///your code behind function
     [System.Web.Services.WebMethod()]
        public static object FunPubGetTasks(string a, string b)
        {
            //return Ienumerable or array   
        }

#7


1  

JS Code:

JS代码:

<script type="text/javascript">
         function ShowCurrentTime(name) {
         PageMethods.GetCurrentTime(name, OnSuccess);
         }
         function OnSuccess(response, userContext, methodName) {
          alert(response);
         }
</script>

HTML Code:

HTML代码:

<asp:ImageButton ID="IMGBTN001" runat="server" ImageUrl="Images/ico/labaniat.png"
class="img-responsive em-img-lazy" OnClientClick="ShowCurrentTime('01')" />

Code Behind C#

在c#代码

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

#8


0  

Try creating a new service and calling it. The processing can be done there, and returned back.

尝试创建一个新的服务并调用它。可以在那里进行处理,然后返回。

http://code.msdn.microsoft.com/windowsazure/WCF-Azure-AJAX-Calculator-4cf3099e

http://code.msdn.microsoft.com/windowsazure/WCF-Azure-AJAX-Calculator-4cf3099e

function makeCall(operation){
    var n1 = document.getElementById("num1").value;
    var n2 = document.getElementById("num2").value;
if(n1 && n2){

        // Instantiate a service proxy
        var proxy = new Service();

        // Call correct operation on vf cproxy       
        switch(operation){

            case "gridOne":
                proxy.Calculate(AjaxService.Operation.getWeather, n1, n2,
 onSuccess, onFail, null);

****HTML CODE****
<p>Major City: <input type="text" id="num1" onclick="return num1_onclick()"
/></p>
<p>Country: <input type="text" id="num2" onclick="return num2_onclick()"
/></p> 
<input id="btnDivide" type="button" onclick="return makeCall('gridOne');" 

#9


0  

In my opinion, the solution proposed by user1965719 is really elegant. In my project, all objects going in to the containing div is dynamically created, so adding the extra hidden button is a breeze:

在我看来,user1965719提出的解决方案非常优雅。在我的项目中,所有进入到包含div的对象都是动态创建的,所以添加额外的隐藏按钮很容易:

aspx code:

aspx代码:

    <asp:Button runat="server" id="btnResponse1" Text="" 
    style="display: none; width:100%; height:100%"
    OnClick="btnResponses_Clicked" />

    <div class="circlebuttontext" id="calendarButtonText">Calendar</div>
</div>    

C# code behind:

c#代码:

protected void btnResponses_Clicked(object sender, EventArgs e)
{
    if(sender == btnResponse1)
    {
        //Your code behind logic for that button goes here
    }
}

#1


36  

Yes, you can make a web method like..

是的,你可以制作一个像…

[WebMethod]
public static String SetName(string name)
{
    return "Your String"
}

And then call it in JavaScript like,

然后用JavaScript,

PageMethods.SetName(parameterValueIfAny, onSuccessMethod,onFailMethod);

This is also required :

这也是必须的:

<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>

#2


22  

In my projects, we usually call server side method like this:

在我的项目中,我们通常调用服务器端方法如下:

in JavaScript:

在JavaScript中:

document.getElementById("UploadButton").click();

Server side control:

服务器端控制:

<asp:Button runat="server" ID="UploadButton" Text="" style="display:none;" OnClick="UploadButton_Click" />

C#:

c#:

protected void Upload_Click(object sender, EventArgs e)
{

}

#3


6  

If you dont want to use ajax than

如果您不想使用ajax,请使用

Code behind 

void myBtn_Click(Object sender,EventArgs e)
{
   //SetName(name); your code
}


.aspx file

<script language="javascript" type="text/javascript">
    function btnAccept_onclick() {        
        var name;            
        name = document.getElementById('txtName').value;
        document.getElementById('callserver').click();
        // Call Server side method SetName() by passing this parameter 'name'
</script>


<div style="dispaly:none;">
  <input type="button" id="callserver" value="Accept" click="myBtn_Click" runat="server" />
</div>
<input type="button" id="btnAccept" value="Accept" onclick="return btnAccept_onclick()" />

or use page method

或使用页面的方法

.cs file
[ScriptMethod, WebMethod]

   public static string docall()
   {
      return "Hello";
   }

.aspx file

<script type="text/javascript">
      function btnAccept_onclic() {
          PageMethods.docall(onSuccess, onFailure);
      }

  function onSuccess(result) {
          alert(result);
      }


      function onFailure(error) {
          alert(error);
      } 

</script>

check this : http://blogs.microsoft.co.il/blogs/gilf/archive/2008/10/04/asp-net-ajax-pagemethods.aspx

检查:http://blogs.microsoft.co.il/blogs/gilf/archive/2008/10/04/asp-net-ajax-pagemethods.aspx

#4


1  

Ajax is the way to go. The easiest (and probably the best) approach is jQuery ajax()

使用Ajax是正确的。最简单(可能也是最好的)方法是jQuery ajax()

You'll end up writing something like this:

你最终会写这样的东西:

$.ajax({
  url: "test.html",
  context: document.body,
  success: function(){
    // do something when done
  }
});

#5


1  

I had to register my buttonid as a postbacktrigger...

我必须将我的buttonid注册为postbacktrigger。

RegisterPostbackTrigger(idOfButton)

#6


1  

// include jquery.js
//javascript function
var a1="aaa";
var b1="bbb";
                         **pagename/methodname**     *parameters*
CallServerFunction("Default.aspx/FunPubGetTasks", "{a:'" + a1+ "',b:'" + b1+ "'}",
            function(result)
            {

            }
);
function CallServerFunction(StrPriUrl,ObjPriData,CallBackFunction)
 {

    $.ajax({
        type: "post",
        url: StrPriUrl,
        contentType: "application/json; charset=utf-8",
        data: ObjPriData,
        dataType: "json",
        success: function(result) 
        {
            if(CallBackFunction!=null && typeof CallBackFunction !='undefined')
            {
                CallBackFunction(result);
            }

        },
        error: function(result) 
        {
            alert('error occured');
            alert(result.responseText);
            window.location.href="FrmError.aspx?Exception="+result.responseText;
        },
        async: true
    });
 }

//page name is Default.aspx & FunPubGetTasks method
///your code behind function
     [System.Web.Services.WebMethod()]
        public static object FunPubGetTasks(string a, string b)
        {
            //return Ienumerable or array   
        }

#7


1  

JS Code:

JS代码:

<script type="text/javascript">
         function ShowCurrentTime(name) {
         PageMethods.GetCurrentTime(name, OnSuccess);
         }
         function OnSuccess(response, userContext, methodName) {
          alert(response);
         }
</script>

HTML Code:

HTML代码:

<asp:ImageButton ID="IMGBTN001" runat="server" ImageUrl="Images/ico/labaniat.png"
class="img-responsive em-img-lazy" OnClientClick="ShowCurrentTime('01')" />

Code Behind C#

在c#代码

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

#8


0  

Try creating a new service and calling it. The processing can be done there, and returned back.

尝试创建一个新的服务并调用它。可以在那里进行处理,然后返回。

http://code.msdn.microsoft.com/windowsazure/WCF-Azure-AJAX-Calculator-4cf3099e

http://code.msdn.microsoft.com/windowsazure/WCF-Azure-AJAX-Calculator-4cf3099e

function makeCall(operation){
    var n1 = document.getElementById("num1").value;
    var n2 = document.getElementById("num2").value;
if(n1 && n2){

        // Instantiate a service proxy
        var proxy = new Service();

        // Call correct operation on vf cproxy       
        switch(operation){

            case "gridOne":
                proxy.Calculate(AjaxService.Operation.getWeather, n1, n2,
 onSuccess, onFail, null);

****HTML CODE****
<p>Major City: <input type="text" id="num1" onclick="return num1_onclick()"
/></p>
<p>Country: <input type="text" id="num2" onclick="return num2_onclick()"
/></p> 
<input id="btnDivide" type="button" onclick="return makeCall('gridOne');" 

#9


0  

In my opinion, the solution proposed by user1965719 is really elegant. In my project, all objects going in to the containing div is dynamically created, so adding the extra hidden button is a breeze:

在我看来,user1965719提出的解决方案非常优雅。在我的项目中,所有进入到包含div的对象都是动态创建的,所以添加额外的隐藏按钮很容易:

aspx code:

aspx代码:

    <asp:Button runat="server" id="btnResponse1" Text="" 
    style="display: none; width:100%; height:100%"
    OnClick="btnResponses_Clicked" />

    <div class="circlebuttontext" id="calendarButtonText">Calendar</div>
</div>    

C# code behind:

c#代码:

protected void btnResponses_Clicked(object sender, EventArgs e)
{
    if(sender == btnResponse1)
    {
        //Your code behind logic for that button goes here
    }
}