Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

c# - How to pass a javascript variable to server side method

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

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"  />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 before you put any value inside the variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...