2

I am writing Razor code in a view, and need to call a JavaScript function with the JSON that is rendered by the Razor code:

// JavaScript function
function buildTemplate(currentTemplate) {
    alert('hello world');
}

@* Build out entire Template structure in JavaScript *@
@foreach (Template template in Model.Templates)
{            
    buildTemplate(JsonConvert.SerializeObject(template));        
}

For some reason, Razor thinks that buildTemplate is a C# method it can't find, and it errors out.

Has anyone done this before? Any advice?

Thanks,

Philip

1
  • Could you not write buildTemplate as a razor helper method using the syntax @helper buildTemplate. You could assign the output to a texbox then read the contents in Jscript? Commented May 31, 2017 at 8:47

2 Answers 2

4

You can either use

@: buildTemplate(@JsonConvert.SerializeObject(template));

or

<text>
buildTemplate(@JsonConvert.SerializeObject(template));
</text>
Sign up to request clarification or add additional context in comments.

Comments

2

Try adding <script> Tags

@* Build out entire Template structure in JavaScript *@
@foreach (Template template in Model.Templates)
{            
    <script>buildTemplate(JsonConvert.SerializeObject(template))</script>        
}

I have not tested this Code

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.