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

xzlaal3s  于 2022-12-20  发布在  .NET
关注(0)|答案(9)|浏览(228)

我有一个JavaScript函数用于ASPX页面中的HTML按钮单击事件。并且在其代码隐藏页面中有一个服务器方法。现在我想仅在用户单击HTML按钮时使用一些参数从JavaScript函数调用服务器方法。
请不要更改此方案,也不要asp.net在回复时在aspx页面中使用任何www.example.com控件。因为只允许使用HTML控件。有人能帮助我吗?
下面是代码,
标记中的代码:

<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()" />

代码隐藏:

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

u1ehiz5o1#

是的,您可以创建一个Web方法,如..

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

然后在JavaScript中调用它,

PageMethods.SetName(parameterValueIfAny, onSuccessMethod,onFailMethod);

这也要求:

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

slwdgvem2#

在我的项目中,我们通常这样调用服务器端方法:
在JavaScript中:

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

服务器端控制:

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

C编号:

protected void Upload_Click(object sender, EventArgs e)
{

}
hgtggwj0

hgtggwj03#

如果你不想使用 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()" />

或使用页面方法

.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>

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

tez616oj

tez616oj4#

JS代码:

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

HTML代码:

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

C#背后的代码

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

ebdffaop5#

我不得不把我的按钮ID注册为后反向触发器...

RegisterPostbackTrigger(idOfButton)
juud5qan

juud5qan6#

AJAX 是一种可行的方法,最简单(也可能是最好)的方法是jQuery ajax()
你最终会写出这样的东西:

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

1yjd4xko7#

尝试创建一个新的服务并调用它。处理可以在那里完成,然后返回。
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');"
knpiaxh1

knpiaxh18#

在我看来,user1965719提出的解决方案非常优雅,在我的项目中,所有进入包含div的对象都是动态创建的,所以添加额外的隐藏按钮是轻而易举的:
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#代码隐藏:

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

xqk2d5yq9#

// 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   
        }

相关问题