Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use properly razor syntax inside script block?

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?

like image 928
Michael Avatar asked Dec 12 '25 06:12

Michael


1 Answers

Because you are already in a C# code block, (opened by your if condition statement). If you want to mix js/plain text with C# code in razor, use @: prefix

If you are trying to generate the relative url to an action method, you should consider using Url.Action method.

<script type="text/javascript">
  var url = '@Url.Action("Login","Account")';
  @if (Request.IsAuthenticated)
  {
      @:url = '@Url.Action("GetLayers","Account")';
  }
</script>

The @: tells razor that the following expression should be considered as not code, but plain text

It is same as using the <text> tag

@if (!Request.IsAuthenticated)
{
   <text>url = '@Url.Action("Index")'</text>;
}

You can convert this to a one liner with ternary operator

<script type="text/javascript">
    var url = '@(Request.IsAuthenticated ? Url.Action("GetLayers","Account") 
                                                   :  Url.Action("Login","Account"))';
    console.log(url);
</script>
like image 121
Shyju Avatar answered Dec 14 '25 20:12

Shyju



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!