Home How to use properly razor syntax inside script block?

# 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">

@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?

• 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