Question

I want to pass viewbag - keyvaluepair data to javascript code.

I tried code below;

<script type="text/javascript">

@foreach (var jtcontentInfo in (List<KeyValuePair<string, string>>)ViewBag.JumpToContentInfo)
    {
        var someStringValue = @jtcontentInfo.Key;   // It works but I cant read it from javascript.
    }

</script>

What is the best way of handling? Any help will be greatly appreciated.

Was it helpful?

Solution

I think you have two problems here.

  1. You are redeclaring someStringValue each iteration of your loop.
  2. You should probably put the key value inside quotes.

Perhaps you can put the values into an array:

<script type="text/javascript">
var values = [];
@foreach (var jtcontentInfo in (List<KeyValuePair<string, string>>)ViewBag.JumpToContentInfo)
    {
        <text>values.push('@jtcontentInfo.Key');</text>
    }
</script>

OTHER TIPS

You can't store directly into a JavaScript variable; you have to remember that the value will merely be printed to the HTML response, and then after the client receives it and IIS has move on to some other task, then the JS will be processed by the browser, and the variable will be set to that value.

So, for example, if @jtcontentInfo.Key was "Foo", the resulting JS would be:

var someStringValue = Foo;

Which would be interpreted as a variable named Foo not the string "Foo". To fix it, you just need to wrap it with quotes:

var someStringValue = "@jtcontentInfo.Key";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top