Mix Razor and Javascript code

前端 未结 7 1815
情歌与酒
情歌与酒 2020-11-22 16:21

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



        
相关标签:
7条回答
  • 2020-11-22 16:45

    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));
    
    0 讨论(0)
  • 2020-11-22 16:47

    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>
    
    0 讨论(0)
  • 2020-11-22 16:51

    Use <text>:

    <script type="text/javascript">
    
       var data = [];
    
       @foreach (var r in Model.rows)
       {
          <text>
                data.push([ @r.UnixTime * 1000, @r.Value ]);
          </text>
       }
    </script>
    
    0 讨论(0)
  • 2020-11-22 16:53

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

    0 讨论(0)
  • 2020-11-22 16:56

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

    0 讨论(0)
  • 2020-11-22 17:05

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

    0 讨论(0)
提交回复
热议问题