user2393454
user2393454

Reputation: 15

How to solve this Javascript/Razor prolem?

I try to add the following javascript code.

 <script> 
    @if (ViewBag.checkedArtikel != null)
    {
        foreach (int ac in ViewBag.checkedArtikel)
        {
            String temp = "'#addartikel" + ac + "'";
            <text> $(@temp).toggleClass('down');</text>
        }
    }
    </script>

If i leave out the script tag i get the right jquery commands:

$('#addartikel1').toggleClass('down');

But with the script tag i get this error:

Uncaught SyntaxError: Unexpected token &

Upvotes: 1

Views: 1617

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

You have very badly mixed server side Razor code with client side javascript. Here's the correct way to do that, by using a JSON serializer:

<script type="text/javascript">
    var articles = @Html.Raw(Json.Encode(ViewBag.checkedArtikel ?? new int[0]));
    $(articles).each(function() {
        $('#addartikel' + this).toggleClass('down');
    });
</script>

Upvotes: 4

Dusan
Dusan

Reputation: 5144

Use this code:

<text>$(@Html.Raw(temp)).toggleClass('down');</text>

Or you can use your old code without adding quotes to variable:

String temp = "#addartikel" + ac;
<text> $('@temp').toggleClass('down');</text>

Upvotes: 1

Related Questions