sukesh
sukesh

Reputation: 2437

assign value to javascript variable from C#

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"]);
    }

Upvotes: 0

Views: 2130

Answers (3)

Imranullah Khan
Imranullah Khan

Reputation: 232

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

Upvotes: 0

user1017882
user1017882

Reputation:

<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.

Upvotes: 1

bemol
bemol

Reputation: 395

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

Upvotes: 0

Related Questions