javascript 如何将javascript变量传递给服务器端方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26988957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:47:12  来源:igfitidea点击:

How to pass a javascript variable to server side method

javascriptc#jqueryasp.net.net

提问by Vignesh

I am facing issue like I am unable to pass the javascript variable to server side I am aware that it is not achieveable in this scenario so I tried like setting the value to the asp hidden field using jQuery and getting the value of the label in server side but unfortunately I am getting empty value for the hidden field. Help me on how to fix this

我面临的问题是我无法将 javascript 变量传递给服务器端我知道在这种情况下无法实现所以我尝试使用 jQuery 将值设置为 asp 隐藏字段并获取服务器中标签的值一边但不幸的是我得到了隐藏字段的空值。帮我解决这个问题

CODE

代码

$(document).ready(function(){
  var DataID = "4325";
    testDataVal(DataID);
});

function testDataVal(DataID){

<%=RenderMethod(DataID) %>  // How to pass javascript variable to server side

}


Hidden Field Approach:

隐场方法:

$(document).ready(function(){
     var DataID = "4325";
    testDataVal(DataID);
});

function testDataVal(DataID){
   $("#<%=hdnDataVal.ClientID %>").val(DataID);

  alert($("#<%=hdnDataVal.ClientID %>").val(DataID));    // Here using javascript I can able to set the value and when I alert the value it is displayed

  <%=RenderMethod(hdnDataVal.Value) %>  // here the hiddenfield value is empty

}

    <asp:HiddenField runat="server" ID="hdnDataVal"  />

回答by Bardo

First of all... you should not mix server code and client code the way you're doing it.

首先......你不应该按照你的方式混合服务器代码和客户端代码。

It's a poor way to design your code. Try always to separate client and server code. They execute on different moments, places and under different circumstances... having them together will eventually draw you to difficult to debug errors.

这是设计代码的一种糟糕方式。始终尝试将客户端和服务器代码分开。它们在不同的时刻、地点和不同的环境下执行……将它们放在一起最终会使您遇到难以调试的错误。

I bet that the problem you're experiencing here is due to this way of coding.

我敢打赌,您在这里遇到的问题是由于这种编码方式。

You say on your code snippet that

你在你的代码片段上说

<%=RenderMethod(hdnDataVal.Value) %>  // here the hiddenfield value is empty

When your page is loading and server code is executed the code inside $(document).ready() is not fired yet, as it fires when your whole page finish loading. So, your RenderMethod is firing beforeyou put any value inside the variable.

当您的页面正在加载并执行服务器代码时,$(document).ready() 中的代码尚未触发,因为它会在您的整个页面加载完成后触发。因此,将任何值放入变量之前,您的 RenderMethod 正在触发。

回答by Samuel Rodrigues

try using $.ajax();

尝试使用 $.ajax();

var url = 'my-url.aspx';
$.ajax({
    url: url,
    type: 'POST',
    data: {'variable_name': my_variable },
    success: function(html)
    { 
      alert('ok');
    },

});

and receiver on the server-side:

和服务器端的接收器:

string my_variable = Request.Form['variable_name'];

回答by Giorgos Betsos

You can use a Page Methodto make a server side call from client side. It's propably the easiest way to accomplish what you want.

您可以使用 aPage Method从客户端进行服务器端调用。这可能是完成你想要的最简单的方法。

First of all you need to include the Script Manager in your aspx page with Page Methodsenabled:

首先,您需要在Page Methods启用的 aspx 页面中包含脚本管理器:

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

Now you can invoke the server side method and pass it the client side data you want, with sth like this:

现在你可以调用服务器端方法并将你想要的客户端数据传递给它,像这样:

<script type="text/javascript">
    $(document).ready(function(){
        var DataID = "4325";
        testDataVal(DataID);
    });

    function testDataVal(DataID) {
        PageMethods.RenderMethod(DataID, OnSuccess, OnError);
    }

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

    function OnError() {
        alert('Some error has ocurred!');
    }
    </script>

OnSuccessfunction is invoked in case the server-side method has been succesfully called. Otherwise OnErrorfunction is invoked.

OnSuccess在成功调用服务器端方法的情况下调用函数。否则OnError调用函数。

This is how the Page Methodshould be declared inside the .aspx.cs file:

这是Page Method应该如何在 .aspx.cs 文件中声明的:

[System.Web.Services.WebMethod]
public static string RenderMethod(string dataID)
{
    return "Got here!";
}

If you place a breakpoint inside RenderMethod, then you can verify that client side data (i.e. value "4325") is correctly passed to it.

如果在 中放置断点RenderMethod,则可以验证客户端数据(即值“4325”)是否正确传递给它。