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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With