0

A comma separated string value is returned from DB and I would like to assign it to a javascript variable. Hidden fields are not an option. Unabele to get the data into js variable. This is what I have tried

ASPX:

<script>
var Collection = <%GetCodes();%>
$(document).ready(function () {
  alert(Collection);
</script>

C#:

public string GetCodes()
    {
        datatable dt = function to get data;
        return Convert.ToString(dt.Rows[0]["codes"]);
    }
2
  • 1
    Have you tried var Collection = '<%=GetCodes();%>';? Commented Oct 30, 2014 at 11:05
  • I get an alert that says 'undefined' Commented Oct 30, 2014 at 11:11

3 Answers 3

1
<script>
var Collection = <%=GetCodes()%>;

$(document).ready(function () {
  alert(Collection);
});
</script>

(Add the =, remove the semi-colon).

Think of the use of = as part of an evaluation (i.e. the return of your GetCodes() method), and without the = as a call on the method without concern with what's returned.

Note also, your parentheses were not balanced, that could've contributed to your problems!? Fixed in my code above anyway.


As an aside: be careful mixing JS and C# in this way. When they're this tightly coupled things can horribly wrong, very fast.

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

1 Comment

The result was a string. So it should be var Collection = '<%=GetCodes()%>'; Thank you very much
0

Value returned from GetCodes() shouldn't be in ' or "?

1 Comment

No they aren't. They are like - abc,def,ghi
0
    <script>
    var Collection = <%=GetCodes()%>;
    $(document).ready(function () {
      alert(Collection); 
});
    </script>

Comments

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.