简体   繁体   English

在razor foreach语句中调用JS函数

[英]call JS function inside razor foreach statement

I have a Model with LevelInfo property: 我有一个带有LevelInfo属性的Model

public IEnumerable<Tuple<string, string, string>> LevelInfo { get; set; }

In the view I have a JS function: 在视图中,我有一个JS函数:

function fillPath(level, color) {
        $('[level=' + level).attr({ 'fill': color });
    }

Now I want to iterate through LevelInfo and call fillPath function: 现在,我要遍历LevelInfo并调用fillPath函数:

$(document).ready(function() {

        @foreach (var info in Model.LevelInfo)
        {
            // How can I call JS function from here?
            // i.e,  fillPath(info.Item1, info.Item2)
        }
    });

Thanks. 谢谢。

Remember, the @foreach is executed server-side and emits HTML for things between { and } . 记住,@ @foreach是在服务器端执行的,并为{}之间的内容发出HTML。

Simply write JavaScript right between the brackets. 只需在括号之间编写JavaScript。

$(document).ready(function() {

    @foreach (var info in Model.LevelInfo)
    {
        fillPath(info.Item1, info.Item2) // Assumes this is a function defined in JavaScript elsewhere
    }
});

Razor is sometimes a bit picky about recognizing a transition from server-side to client-side code. Razor有时对识别从服务器端代码到客户端代码的过渡有些挑剔。 You may need to wrap the JavaScript code in <text> to help Razor along. 您可能需要将JavaScript代码包装在<text>以帮助Razor。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM