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

How to use properly razor syntax inside script block?

Michael
1#
Michael Published in 2017-11-13 19:55:39Z

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?

Shyju
2#
Shyju Reply to 2017-11-13 20:18:57Z

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>
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO