1

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.

1
  • You want to call fillPath on the server or the client? Commented Jun 7, 2012 at 6:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.