Mix Razor and Javascript code

C#JavascriptRazor

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

Use <text>:

<script type="text/javascript">

   var data = [];

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

Solution 2 - C#

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, ...)

Solution 3 - C#

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 @:

Solution 4 - C#

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]);
    }

In case of problem you can also try

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

Solution 5 - C#

A non conventional method to separate javascript from the view, but still use razor in it is to make a Scripts.cshtml file and place your mixed javascript/razor there.

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>

Solution 6 - C#

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

Solution 7 - C#

This is my way to hack Razor and use Javascript without freaking out Intellisense.

Obviously you should use <text> but with an "expedient": double braces before.

This is what happens if a single brace is used:

enter image description here

This is what happen if a couple of braces are used:

enter image description here

Now constants and variable have been recognized. It's better, but not good! There is still the "less than" symbol that confuses intellisense making it think that following is the name of a tag. The "less than" sign is signaled as error and from here there are parsing errors as "console.log" shows. You need to add something that quiets intellisense and doesn't get returned in the final JS code at compile time.

Solution: use this comment after "less than": /*>*/

This is the result

enter image description here

It's quite strange to see, but it works as it should.

Solution 8 - C#

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 =(

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyle BrandtView Question on Stackoverflow
Solution 1 - C#Max ToroView Answer on Stackoverflow
Solution 2 - C#SLaksView Answer on Stackoverflow
Solution 3 - C#Medet TleukabilulyView Answer on Stackoverflow
Solution 4 - C#MertuarezView Answer on Stackoverflow
Solution 5 - C#Joel WiklundView Answer on Stackoverflow
Solution 6 - C#Code With SuriView Answer on Stackoverflow
Solution 7 - C#tedebusView Answer on Stackoverflow
Solution 8 - C#spine4illerView Answer on Stackoverflow