Home How to use properly razor syntax inside script block?
Reply: 0

How to use properly razor syntax inside script block?

user7248
1#
user7248 Published in September 19, 2018, 3:18 am

I work on an ASP.NET MVC 5 project.

I try to use razor syntax in script area on the cshtml page:

<script type="text/javascript">
    var url = '@Url.Content("~/Account/Login/")';

    @if (Request.IsAuthenticated)
     {
          url = '@Url.Content("~/Account/GetLayers/")';
     }
</script>

But when I run the page I get on this row:

url = '@Url.Content("~/Account/GetLayers/")';

This error:

CS1012: Too many characters in character literal

So I tried this:

 url = "@Url.Content("~/Account/GetLayers/")";

But now I get this error:

CS1002: ; expected

Any idea why my attempts above don't work?

share|improve this question
  • Mixing JS & Razor code is confusing and prone to XSS. You should pass values from the server using data- attributes instead. – SLaks Nov 13 '17 at 19:58
  • var isRequested = @Html.Raw(Json.Encode(Request.IsAuthenticated) if(isRequested) { .... – Stephen Muecke Nov 13 '17 at 19:59

1 Answer 1

active oldest votes
up vote 2 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.35201 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO