Mix Razor and Javascript code

2018-12-31 19:38发布

问题:

I\'m pretty confused with how to mix razor and js. This is the current function I am stuck with:

<script type=\"text/javascript\">

        var data = [];

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

If I could declare c# code with <c#></c#> and everything else was JS code -- this would be what I am after:

<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 best method to achieve this?

回答1:

Use <text>:

<script type=\"text/javascript\">

   var data = [];

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


回答2:

Inside a code block (eg, @foreach), you need to mark the markup (or, in this case, Javascript) with @: or the <text> tag.

Inside the markup contexts, you need to surround code with code blocks (@{ ... } or @if, ...)



回答3:

you also can simply use

<script type=\"text/javascript\">

   var data = [];

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

note @:



回答4:

Never ever mix more languages.

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

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


回答5:

you can use the <text> tag for both cshtml code with javascript



回答6:

Wrap your Razor code in @{ } when inside JS script and be aware of using just @ Sometimes it doesn\'t work:

function hideSurveyReminder() {
       @Session[\"_isSurveyPassed\"] = true;
    }

This will produce

function hideSurveyReminder() {
       False = true;
    }

in browser =(