Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...