1

I have the following statement:

<script type="text/javascript">
            @{
                string area = ViewContext.RouteData.DataTokens["area"] != null ? 
                    ViewContext.RouteData.DataTokens["area"].ToString().ToLower() : 
                    string.Empty;
            }


        var area = "@area";

</script>

and my Google Chrome, if I call area variable in console, displays like:

" != null ? ViewContext.RouteData.DataTokens["area"].ToString().ToLower() : """

which is a part of C# code ...

Where is the mistake ?

Snake Eyes
  • 16,287
  • 34
  • 113
  • 221

1 Answers1

2

There is a problem when you are trying to use the razor inside script blocks.

There is an amazing answer of the issue here: Razor Syntax and Javascript

So you should either modified your code to

 @{
    string area = ViewContext.RouteData.DataTokens["area"] != null ? 
                  ViewContext.RouteData.DataTokens["area"].ToString().ToLower() : 
                  string.Empty;
  }
<script type="text/javascript">               
    var area = "@area";    
</script>

Or to wrap your code in a pseudo block (or @: if you are using the newer version of MVC)

<script type="text/javascript">
            @{
              <text>  string area = ViewContext.RouteData.DataTokens["area"] != null ? 
                    ViewContext.RouteData.DataTokens["area"].ToString().ToLower() : 
                    string.Empty;</text>
            }    

        var area = "@area";    
</script>
Community
  • 1
  • 1
nsgocev
  • 4,390
  • 28
  • 37