2

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Michael
  • 13,950
  • 57
  • 145
  • 288
  • 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) { ....` –  Nov 13 '17 at 19:59

1 Answers1

8

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>
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • thanks for post! can you please explain?What you mean ready in a code block? – Michael Nov 13 '17 at 19:58
  • Why?What is difference? – Michael Nov 13 '17 at 20:02
  • What is difference if I use Url.Action or @Url.Content? – Michael Nov 13 '17 at 20:08
  • https://stackoverflow.com/questions/8186163/mvc-url-content-vs-url-action – Shyju Nov 13 '17 at 20:11
  • You opened a c# code block by starting `@if (Request.IsAuthenticated)`. If you want to mix plain text inside that, you ned to use `` – Shyju Nov 13 '17 at 20:14
  • 1
    Since the methods are the same, why not use the ternary operator inside the method? `var url = @Url.Action(Request.IsAuthenticated ? "GetLayers" : "Login", Account")`. Depending on where this code is being executed, it might be better in the controller anyway. – Erik Philips Nov 13 '17 at 20:19
  • Yes. That will work too here as both of this actions are from same controller. All it needs is a string (for the action name). – Shyju Nov 13 '17 at 20:21