1

I have created a razor view (Demo.cshtml) and I tried to declare razor variable within javascript block as shown below:

Code:

@{
    ViewBag.Title = "Demo";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
    Demo</h2>

<script type="text/javascript">
    $(function () {
        @{
            bool test = true;
         }

    });
</script>

I am getting few warnings as mentioned below:

Warning 1 Invalid character Demo.cshtml 10 10 Warning 2 Expected ';' Demo.cshtml 11 18

Can anyone guide me in resolving the above warning?

2
  • why you want to use a razor view inside javascript, when you can already declare variables in javascript? Commented Aug 14, 2014 at 11:47
  • 1
    I am trying to use the razor variable within the javascript function. Commented Aug 14, 2014 at 12:03

1 Answer 1

1

Well its not so easy to explain. For different needs you can use different solutions.

The easiest way is to use 'text' tag:

<script type="text/javascript">
    @{
        <text>

        alert(@myVar);

        </text>
    }

</script>

And for example for String values you can do like

<script type="text/javascript">
    var url = '@Url.RouteUrl("admin", new { controller = "users"})';
</script>

For boolean types you can do like in this example, but it looks like a stupid hack :)

var bool = '@ViewData.ModelState.IsValid' == "True";

And for collections you need to implement some helper method to be able to call

var myArray = @Html.ToJson(MyCSharpCollectionObject)
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.