Coder Perfect

Use a combination of Razor and Javascript code.

Problem

I’m not sure how to use razor and js together. I’m now stuck with the following function:

<script type="text/javascript">

        var data = [];

        @foreach (var r in Model.rows)
        {
                data.push([ @r.UnixTime * 1000, @r.Value ]);
        }

This is what I’m after: If I could declare c# code with c#>/c#> and everything else was JS code:

<script type="text/javascript">

        var data = [];

        <c#>@foreach (var r in Model.rows) {</c#>
                data.push([ <c#>@r.UnixTime</c#> * 1000, <c#>@r.Value</c#> ]);
        <c#>}</c#>

What is the most effective way to accomplish this?

Asked by Kyle Brandt

Solution #1

Use :

<script type="text/javascript">

   var data = [];

   @foreach (var r in Model.rows)
   {
      <text>
            data.push([ @r.UnixTime * 1000, @r.Value ]);
      </text>
   }
</script>

Answered by Max Toro

Solution #2

Mark the markup (or, in this case, Javascript) with @: or the text> element inside a code block (e.g., @foreach).

You must enclose code with code blocks (@… or @if,…) within the markup contexts.

Answered by SLaks

Solution #3

Alternatively, you can use

<script type="text/javascript">

   var data = [];

   @foreach (var r in Model.rows)
   {
       @:data.push([ @r.UnixTime * 1000, @r.Value ]);
   }
</script>

note @:

Answered by Medet Tleukabiluly

Solution #4

Never, ever, ever, ever, ever, ever, ever, ever, ever, ever

<script type="text/javascript">
    var data = @Json.Encode(Model); // !!!! export data !!!!

    for(var prop in data){
      console.log( prop + " "+ data[prop]);
    }

You can also try if you have a problem.

@Html.Raw(Json.Encode(Model));

Answered by Mertuarez

Solution #5

Making a Scripts.cshtml file and putting your mixed javascript/razor in it is a non-traditional way to isolate javascript from the view while still using razor.

Index.cshtml

<div id="Result">
</div>

<button id="btnLoad">Click me</button>

@section scripts
{
    @Html.Partial("Scripts")
}

Scripts.cshtml

<script type="text/javascript">
    var url = "@Url.Action("Index", "Home")";

    $(document).ready(function() {
        $("#btnLoad").click(function() {
            $.ajax({
                type: "POST",
                url: url ,
                data: {someParameter: "some value"},
                contentType: "application/json; charset=utf-8",
                dataType: "json",

                success: function(msg) {
                    $("#Result").text(msg.d);
                }
            });
        });
    });
</script>

Answered by Joel Wiklund

Post is based on https://stackoverflow.com/questions/5614941/mix-razor-and-javascript-code