3

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('<%=completeURL%>', 
     function(d) {
       $(d).find('entry').each(function(){
         var $entry = $(this);
         var pic = $entry.find('content').attr('src');
         alert(pic);
       });
     });
   });
 </script>

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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";

2 Comments

This is what I need help for. I've already created one such field but the question is how to assign it the value from script now?
@ankitaalung, $('#yourcontrolId').val(pic);
0

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('<%=completeURL%>', 
     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;

3 Comments

Makes sense to me, let me try it first.
it's still giving me empty string after debugging it.
in what event are you trying to get this value, can you post the full code you are using ?, both cs and asp.net if possible

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.