santosh kumar patro
santosh kumar patro

Reputation: 8241

How to declare a variable with razor syntax within javascript block for a razor view?

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?

Upvotes: 1

Views: 1514

Answers (1)

maxs87
maxs87

Reputation: 2284

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)

Upvotes: 1

Related Questions