Using Razor within JavaScript

后端 未结 12 2575
萌比男神i
萌比男神i 2020-11-22 04:12

Is it possible or is there a workaround to use Razor syntax within JavaScript that is in a view (cshtml)?

I am trying to add markers to a Google map...

12条回答
  •  清歌不尽
    2020-11-22 04:58

    Use the pseudo-element, as described here, to force the Razor compiler back into content mode:

    
    

    Update:

    Scott Guthrie recently posted about @: syntax in Razor, which is slightly less clunky than the tag if you just have one or two lines of JavaScript code to add. The following approach would probably be preferable, because it reduces the size of the generated HTML. (You could even move the addMarker function to a static, cached JavaScript file to further reduce the size):

    
    

    Updated the above code to make the call to addMarker more correct.

    To clarify, the @: forces Razor back into text mode, even though addMarker call looks a lot like C# code. Razor then picks up the @item.Property syntax to say that it should directly output the contents of those properties.

    Update 2

    It's worth noting that View code really isn't a good place to put JavaScript code. JavaScript code should be placed in a static .js file, and then it should get the data that it needs either from an Ajax call or by scanning data- attributes from the HTML. Besides making it possible to cache your JavaScript code, this also avoids issues with encoding, since Razor is designed to encode for HTML, but not JavaScript.

    View Code

    @foreach(var item in Model)
    {
        
    }

    JavaScript code

    $('[data-marker]').each(function() {
        var markerData = $(this).data('marker');
        addMarker(markerData.Latitude, markerData.Longitude,
                  markerData.Description, markerData.Title);
    });
    

提交回复
热议问题