admin管理员组

文章数量:1354748

I have a Model with LevelInfo property:

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

In the view I have a JS function:

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

Now I want to iterate through LevelInfo and call fillPath function:

$(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.

I have a Model with LevelInfo property:

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

In the view I have a JS function:

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

Now I want to iterate through LevelInfo and call fillPath function:

$(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.

Share Improve this question asked Jun 7, 2012 at 6:35 user1260827user1260827 1,5206 gold badges31 silver badges53 bronze badges 1
  • You want to call fillPath on the server or the client? – leppie Commented Jun 7, 2012 at 6:36
Add a ment  | 

1 Answer 1

Reset to default 8

Remember, the @foreach is executed server-side and emits HTML for things between { and }.

Simply write JavaScript right between the brackets.

$(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. You may need to wrap the JavaScript code in <text> to help Razor along.

本文标签: javascriptcall JS function inside razor foreach statementStack Overflow