在 JavaScript 中使用 Razor [英] Using Razor within JavaScript

查看:30
本文介绍了在 JavaScript 中使用 Razor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在视图 (cshtml) 中的 JavaScript 中是否可以使用 Razor 语法或是否有解决方法?

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

我正在尝试向 Google 地图添加标记...例如,我尝试过此操作,但出现大量编译错误:

I am trying to add markers to a Google map... For example, I tried this, but I'm getting a ton of compilation errors:

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.

    // Now add markers
    @foreach (var item in Model) {

        var markerlatLng = new google.maps.LatLng(@(Model.Latitude), @(Model.Longitude));
        var title = '@(Model.Title)';
        var description = '@(Model.Description)';
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>'

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }
</script>

推荐答案

使用 伪元素,如此处,强制 Razor 编译器返回内容模式:

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

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.


    // Now add markers
    @foreach (var item in Model) {
        <text>
            var markerlatLng = new google.maps.LatLng(@(Model.Latitude), @(Model.Longitude));
            var title = '@(Model.Title)';
            var description = '@(Model.Description)';
            var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>'

            var infowindow = new google.maps.InfoWindow({
                content: contentString
            });

            var marker = new google.maps.Marker({
                position: latLng,
                title: title,
                map: map,
                draggable: false
            });

            google.maps.event.addListener(marker, 'click', function () {
                infowindow.open(map, marker);
            });
        </text>
    }
</script>

更新:

Scott Guthrie 最近发布了关于 Razor 中的 @: 语法,如果您只需添加一两行 JavaScript 代码.以下方法可能更可取,因为它减少了生成的 HTML 的大小.(您甚至可以将 addMarker 函数移动到静态、缓存的 JavaScript 文件以进一步减小大小):

Scott Guthrie recently posted about @: syntax in Razor, which is slightly less clunky than the <text> 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):

<script type="text/javascript">

    // Some JavaScript code here to display map, etc.
    ...
    // Declare addMarker function
    function addMarker(latitude, longitude, title, description, map)
    {
        var latLng = new google.maps.LatLng(latitude, longitude);
        var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>';

        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: latLng,
            title: title,
            map: map,
            draggable: false
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });
    }

    // Now add markers
    @foreach (var item in Model) {
        @:addMarker(@item.Latitude, @item.Longitude, '@item.Title', '@item.Description', map);
    }
</script>

更新了上面的代码,使addMarker的调用更加正确.

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

澄清一下,@: 强制 Razor 回到文本模式,即使 addMarker 调用看起来很像 C# 代码.然后 Razor 使用 @item.Property 语法说它应该直接输出这些属性的内容.

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.

值得注意的是,View 代码确实不是放置 JavaScript 代码的好地方.JavaScript 代码应该放在一个静态的 .js 文件中,然后它应该从 Ajax 调用或通过扫描 HTML 中的 data- 属性获取它需要的数据.除了可以缓存 JavaScript 代码之外,这还避免了编码问题,因为 Razor 旨在为 HTML 编码,而不是 JavaScript.

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.

@foreach(var item in Model)
{
    <div data-marker="@Json.Encode(item)"></div>
}

JavaScript 代码

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

这篇关于在 JavaScript 中使用 Razor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆