Executing JavaScript functions from an ASP.NET Razor view is achieved by using the

While working on a view in which I am writing Razor code, I encountered the need to call a JavaScript function with the JSON generated 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));        
}

However, Razor seems to be confusing buildTemplate as a C# method that it cannot locate, resulting in an error.

Has anyone faced a similar issue before? Any suggestions or advice would be greatly appreciated.

Thank you,

Philip

Answer №1

There are two options available for implementing this:

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

Alternatively, you can also use:

<text>
buildTemplate(@JsonConvert.SerializeObject(template));
</text>

Answer №2

Experiment with Including <script> Tags

@* Construct the complete Template framework using JavaScript *@
@foreach (Template template in Model.Templates)
{            
    <script>buildTemplate(JsonConvert.SerializeObject(template))</script>        
}

This Code has yet to be validated

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Include and remove JSON data items within ng-repeat loop

I am in the process of creating a dynamic page where users can add multiple locations to their contact information. Currently, my code looks like this: <div class="input-append" ng-repeat="location in newPartner.partner_location"> <input clas ...

Challenge with Vite, React, and MSW Integration

Having some trouble setting up MSW in a React application. It's unusual for me to come across issues like this. I've configured an environment variable VITE_MOCK set to true when running the yarn start:mock command. This should enable API mocking ...

The Double Negation operator

While reading a book, I came across this code snippet: !!(document.all && document.uniqueID); I'm wondering why the double not operator is used here. Doesn't the && operator already convert the result to a Boolean? ...

Setting up multiple RabbitMQ or other backend servers within Node configurations

As someone working in DevOps, I have encountered a situation where our developers are claiming that the Node.js software they wrote can only point to a single backend server due to Node.js limitations. This assertion seems unbelievable to me. How is it eve ...

"Bringing together ECMA harmony: a nod to callbacks and generators

Initially, we are exploring uncharted territory here. Although it functions in the latest versions of Firefox, the documentation on MDN is not yet ready at the time of writing. I will address the MDN later on (maybe, as there are numerous areas needing att ...

Tips for creating tree diagrams for JSON data with D3.js?

I am eager to represent intricate nested JSON objects as tree diagrams using D3.js. Most examples utilize JSON files that explicitly outline their hierarchy, such as through the children attribute: { "name":"Alex", "children& ...

Embed the variable directly within the JSON structure

My goal is to dynamically create a JavaScript object using object initializer notation, but with keys taken from a config object. Instead of the traditional method: var obj = { 'key' : 'some value' }; I envision something like this: ...

HTML filtering using the <select> element

Is there a way to implement this script for options instead of buttons? The goal is to filter the HTML section, but it seems to not work with <option> tags. Instead of displaying the all class, it shows nothing. CSS .show { display: block; } .filt ...

Managing and retrieving data in bulk from an indexed database as JSON format

I am currently developing an application that utilizes IndexexDB for local data storage. I am looking for a way to extract and insert large amounts of data from an indexed DB in JSON format. Below is the code snippet illustrating what I have accomplished s ...

Exploring the implementation of toggling functionality for nested children within <li> elements using jQuery

Unable to get the toggle function working on child nodes. Can someone assist me with this issue? $(document).ready(function() { $('label.tree-toggler').click(function() { $(this).parent().children('ul.tree').toggle(300); }); ...

Creating a decorative ribbon in three.js for your gift presentation

How can I create a ribbon for a gift box using three.js, similar to the example shown here: Is it possible to create the ribbon with just one piece or do I need multiple pieces to achieve the desired look? Thank you :) ...

Retrieve all items pertaining to a specific week in the calendar

I'm trying to obtain a list of week ranges for all data in my MongoDB. When a week range is clicked, only the records for that specific week range should be displayed. By clicking on the week range, the ID of the week (let's say 42, representing ...

Ways to verify audio in several HTML5 video files

I am working on a way to determine if multiple videos have audio or not. Here is an example of what I have so far: https://jsfiddle.net/hrd4a0c3/ However, my current solution only checks one video at a time. I am looking for a way to extend this functiona ...

Exploring the power of nested generic lambdas within LINQ

I'm struggling to grasp the concept of Expressions in LINQ and would really appreciate any guidance (even if it means correcting my understanding). Let's consider three classes in this scenario: public class Person { public string Name { ge ...

Exploring navigation options in VueJS with the router

I recently completed a tutorial on integrating Okta OAuth with VueJS. In my application, I have set up a default page that displays the "App.vue" component and switches to the "About.vue" component upon clicking the "/about" route. However, I encountered a ...

Stopping a jQuery AJAX request after receiving another response

I am facing a problem and I need some creative solutions :) Currently, I have two $.ajax calls in my code. The first call is asynchronous and takes a long time to respond (approximately 1 minute). On the other hand, the second call is synchronous (with as ...

Make the background disappear when the text field is left empty and the cursor is not present (onUnfocus)

When the text field is empty and there is no cursor in the text field, I want it to be transparent and for the spell checker not working. The result should be displayed a little to the left inside a <div>. Should this be done using CSS, JavaScript, ...

What is the best way to incorporate a state variable into a GraphQL query using Apollo?

My current challenge involves using a state as a variable for my query in order to fetch data from graphQl. However, I'm encountering an issue where the component does not read the state correctly. Any suggestions on how to solve this? class usersSc ...

The issue I am facing is that the MDCSelect:change event does not seem to be functioning properly

Is there a way to get MDCSelect:change to work properly before appending all options? If I put MDCSelect:change after the list append, it works but the UI doesn't look right. Question: How can I make MDCSelect:change work without affecting the UI ap ...

I'm looking to create a redirect feature using a QR code that will direct users to a specific page within my Flutter app. How

When the user scans the QR code, they will be taken to a secret internal page that can only be accessed through this specific link. I attempted to use various libraries such as , but it did not achieve the desired outcome. ...