Top method for transferring server (C# / Razor) data to an AngularJS application

In our use of DNN, we often encounter the need to pass specific context values (such as page id or module-on-page-id) into an AngularJS application. While we have established our own conventions for achieving this, we are interested in hearing about how others approach this in order to determine best practices.

The core issue is that the server-side page possesses information required by the JavaScript. Utilizing WebAPI is not viable, as these values are only known within the page itself and not through a separate request. Some methods I have come across include:

  1. Utilizing in-view-razor like href="@Tab.TabId/{{...}}" (although I am not fond of this approach)
  2. Embedding the values in the ng-init attribute such as
    ng-init="config = { prop1: '@Tab.TabId' }"
  3. Creating a dynamic module within a separate <script> tag which contains these values like so:
    angular.module("config", []).constant('prop1', '@Tab.TabId')
  4. Generating a JSON with razor within the page, and then injecting it as a module into the app using a generic code similar to #3, but with cleaner code re-use

I have encountered all of these methods and have tested them all. Currently, we shy away from option #1 due to concerns about mixing templating languages and the inability to externalize parts of the view. Our current practice involves utilizing #2 for quick-and-simple tasks (albeit somewhat messy), and implementing #3/#4 for larger projects.

Do you have a more effective approach, or which method do you prefer?

Answer №1

Our selection falls on variant #4.

One notable benefit is that the JSON delineates the precise interface for the configuration required by the JS module. Additionally, Razor proves to be a powerful tool in crafting URLs with @Url.Action.

Answer №2

Our preferred method involves utilizing NewtonSoft's JSONConvert.SerializeObject(ObjectName) to convert the object into a JSON format. This JSON data is then passed over as a Session from the controller. Finally, we can easily access and manipulate this JSON object in JavaScript using @Html.Raw(ObjectName).

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

Accessing attribute value of selected option in AngularJS select element

I have a select tag that displays options, and I want it so that when an option is selected, the value of the data-something attribute is copied into the input element. This is just for demonstration purposes; the actual value should be sent in the form. ...

"Enhancing JqGrid functionality with inline editing and custom formatters

I'm currently working with a column model that looks like this: { name: 'CostShare', index: 'CostShare', width: 50, formatter: 'number', formatoptions: { decimalPlaces: 2, suffix: "%" }, resizeable: true, align: 'ce ...

I prefer to avoid generating the document structure while parsing with JSOUP

Utilizing the Jsoup API to parse a section of HTML using the Jsoup.parse() method. However, during parsing, it includes the document structure in the HTML content. For Instance: <p><a href="some link">some link data</a> Some paragraph c ...

Performing a targeted ajax request to retrieve a set of data

Is it possible to create a collection using a specific ajax call instead of fetching by its URL? Normally, when fetching by a collection, the URL in the collection is used. However, I need to retrieve results from an ajax call rather than the URL. $.ajax( ...

"Dealing with Protractor's promises can be a headache when trying to

Our web tool features multiple html forms, each encompassing a set of form fields. I am exploring ways to use Protractor to extract the list of field labels, input types (such as textboxes, select dropdowns, radio buttons), and input controls for setting v ...

Dealing with blank values in jQuery DataTables

I am currently utilizing jQuery DataTable to display data in table format; within the table, there is a button that triggers a Bootstrap Modal for editing two of these values, and I utilize Ajax to send the modified values to a Spring Controller. The init ...

When utilizing ControllerAs, the directive parameters are replaced with new values

Trying to implement a directive with different parameter values, but the first parameter is being overridden by the second one. This is the parent HTML: <div finals-match-row team="foo"></div> <div finals-match-row team="bar"></div&g ...

I'm intrigued by this maneuver, but I am uncertain about its safety when used in JavaScript

I am currently contemplating the safety and reliability of assigning a variable within an if statement across different browsers. If it proves to be safe, then I am inclined to proceed with its usage. The scenario involves reading the query string and che ...

Determining If a setInterval Function is the Sole Factor Preventing an App from Exiting

Is there a method to determine the number of tasks remaining for Node before it automatically exits because all tasks are completed? I am interested in utilizing setInterval but only while the application is still running other processes. I do not want t ...

Adjust the color of TextareaAutosize component using mui in React

Just starting out with React and getting acquainted with mui components. Experimenting with setting the color of a TextareaAutosize mui component using this code: import * as React from 'react'; import TextareaAutosize from '@mui/material/T ...

What is the best way to retrieve the name of an element or component using JavaScript

I'm currently working on a webpage that includes ASP.NET panels and JavaScript which retrieves all components present on the page: var items = Sys.Application.getComponents(); My goal is to obtain the name/ID of each element stored in the 'item ...

What could be the reason for express-validator's inability to identify missing fields during the validation of XML input

My server, based on Express, is set up to parse XML instead of JSON using body-parser-xml. To validate the input body, I am using express-validator as shown in the following simplified example: router.post("/", body('session.credential[0].$.usern ...

Prevent the submit button from being clicked again after processing PHP code and submitting the form (Using AJAX for

I've set up a voting form with submit buttons on a webpage. The form and PHP code work fine, and each time someone clicks the vote button for a specific option, it gets counted by 1. However, the issue is that users can spam the buttons since there i ...

A scheduled task in Node.js set to run every day at 2 AM

My nodejs cron currently runs every 5 hours using the code below: cron.schedule("0 0 */5 * * *") How can I modify it to run daily at 2 AM instead? Thank you ...

How can I efficiently iterate through the array of index IDs and then iterate individually through the communes, categories, and locations?

Currently, I am developing a nodejs typescript API where I am retrieving an array of objects using a map loop. The data for "communes", "category", and "location" is fetched from another API function based on the issuerId. However, I am facing issues with ...

A Guide on How to Sort and Tally Items in a JSON Data Set containing Numerous Objects using JavaScript

I have recently started learning javascript, and everything was going well until I encountered this issue. I need to reformat a JSON file in the following structure: { firstName: "Joel", lastName: "Munz", total: 154, transaction: "111111", ...

Tips for Accessing the TextInput Content in React Native

My code is currently experiencing a bug where I am getting an undefined object type when trying to console log user input. Below is the code snippet I am working with. Can you help me identify and correct the issue? export default function App() { con ...

What is the best way to modify a newly added element using jQuery?

When a user clicks a button on my screen, a new template is loaded dynamically using jQuery's .load() method. This transition adds new HTML to the page that was not present when the script initially loaded: (function($) { $('.go').on("c ...

Tips for showcasing Markdown files within subdirectories in Next.JS

In my Next.JS project, I am managing numerous Markdown files that are organized into various category folders. For example, I have folders named 'CategoryOne' and 'CategoryTwo' located at the root level of the project alongside node_mod ...

When executed through nodeJS using the `require('./main.ts')` command, TypeScript Express encountered an issue with exporting and displayed undefined

Describing my issue is proving to be challenging, so I have simplified the code. Let me share the code below: main.ts import express from 'express'; let a = 1 console.log ('a in main.ts', a) export let b = a const app = express() let ...