admin管理员组

文章数量:1327843

I am trying to access the script variable pic and assign it to another variable in C#, say hidden field hdn. The script below is also placed on the same code behind page for some reason. I can directly access the hidden field here. But how do I assign it value from the script variable?

 <script type=\"text/javascript\">
   $(document).ready(function() {
     $.get('<%=pleteURL%>', 
     function(d) {
       $(d).find('entry').each(function(){
         var $entry = $(this);
         var pic = $entry.find('content').attr('src');
         alert(pic);
       });
     });
   });
 </script>

I am trying to access the script variable pic and assign it to another variable in C#, say hidden field hdn. The script below is also placed on the same code behind page for some reason. I can directly access the hidden field here. But how do I assign it value from the script variable?

 <script type=\"text/javascript\">
   $(document).ready(function() {
     $.get('<%=pleteURL%>', 
     function(d) {
       $(d).find('entry').each(function(){
         var $entry = $(this);
         var pic = $entry.find('content').attr('src');
         alert(pic);
       });
     });
   });
 </script>
Share Improve this question edited Sep 24, 2013 at 9:36 dav_i 28.2k17 gold badges110 silver badges138 bronze badges asked Sep 24, 2013 at 9:32 ankita alungankita alung 3273 gold badges6 silver badges20 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 1

There is no way to assign a C# variable by javascript. You have to send that value from the client (where you JavaScript is running) to the Server, and assign it. This is so called ajax request, just google it and you'll find millions of good examples of how to achieve that.

create a hidden filed and then set the value from javascript

 <asp:hiddenfield id="hf_MyValue"
          value="whatever" 
          runat="server"/>

How To Set value in javascript

//get value from hidden filed
var test= document.getElementById('<%= hf_MyValue.ClientID %>');
//set value in hidden filed
document.getElementById('<%= hfBrand.ClientID %>').value = "True";

Create a hidden variable like this,

<input type="hidden" id="hdnVariable" runat="server" />

Now try this code

<script type=\"text/javascript\">
   $(document).ready(function() {
     $.get('<%=pleteURL%>', 
     function(d) {
       $(d).find('entry').each(function(){
         var $entry = $(this);
         var pic = $entry.find('content').attr('src');
         //assign value to server side hidden variable
         $("#<%=hdnVariable.ClientID%>").val(pic);
       });
     });
   });
 </script>

Now you can access this hidden field from C# code like this

string pic=hdnVariable.Value;

本文标签: Assigning C variable value using javascript variable in code behindStack Overflow