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 ?

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.