-1

I have to use javascript code inside Razor. The code is:

@if (element.ParentItemID == null)
{
    <script type="text/javascript">
        $(window).resize(function () {
            if ($(window).width() > 640) {
                @Html.ActionLink(element.PageTitle, "Details", "Items", new { @parentitem = "website", @url = (element.Url) }, new { @class = "" })
            }
            else {
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">@element.PageTitle</a>
            }
        }); //show syntax error
    </script>
}

Without javascript code , it generates a Menu. But when I use code above it shows nothing.

I tried solution here, but its not working in this case: Mix Razor and Javascript code

Community
  • 1
  • 1
kpr
  • 451
  • 5
  • 17

1 Answers1

0

Your javascript block needs to be separate from your html. With the current implementation the browser will try to interpret the html as invalid javascript and nothing will happen. Try toggling the elements or swapping out the href attribute.

@if (element.ParentItemID == null)
{
    <script type="text/javascript">
        $(window).resize(function ()
        {
            var isWideEnough = $(window).width() > 640;
            $(".isWideEnough").toggle(isWideEnough);
            $(".isNotWideEnough").toggle(!isWideEnough);
        });
    </script>

    @Html.ActionLink(element.PageTitle, "Details", "Items", new { @parentitem = "website", @url = (element.Url) }, new { @class = "isWideEnough" })
    <a href="#" class="dropdown-toggle isNotWideEnough" data-toggle="dropdown">@element.PageTitle</a>
}
jtimperley
  • 2,494
  • 13
  • 11