AngularJS - one-time execution of view generation from .NET controller

Currently, I have an MVC .NET application integrated with AngularJS. In my route provider configuration, I am utilizing the controllers of MVC to retrieve the views as shown below:

   .when('/Units', {
        templateUrl: 'Unit/Units'
    })
    .when('/UnitsDetail', {
        templateUrl: 'Unit/UnitsDetail'
    })

My UnitController in .NET consists of the following methods:

 [Authorize]
    public ActionResult Units()
    {
        return View();
    }

    [Authorize]
    public ActionResult UnitsDetail()
    {
        ViewBag.reference = Guid.NewGuid().ToString().Substring(0, 6);
        return View();
    }

In the UnitsDetail view, it is necessary for me to have a unique reference generated within the UnitsDetail() method.

An issue arises when navigating from Units to UnitsDetail multiple times. Initially, the UnitsDetail() method is invoked, generating a new reference. However, upon returning to Units and revisiting UnitsDetail, the method is not triggered again resulting in the same reference being displayed. It is imperative that a fresh reference is generated each time.

Although I could potentially generate the reference using JavaScript on the client side or make an AJAX request from Angular to the server, my main query revolves around how to prompt Angular to call the UnitsDetail() method whenever "#/UnitsDetail" is accessed.

Any insights or suggestions would be greatly appreciated!

Answer №1

By default, Angular will store all views in its template cache for faster access.

This caching behavior is intentional on Angular's part. The framework expects the view to contain mostly static HTML with dynamic elements indicated by {{ dynamicScopeVariable }}. When rendering the view, Angular will replace the dynamic parts with values from scope objects while displaying the static content directly from the cache.

Upon the first execution of a view, it will be cached for future use.

In terms of design considerations, you have two options available, with one clear choice being more favorable:

Option #1

Disable template caching in Angular by following instructions at

By disabling caching, Angular will fetch the HTML template every time it is needed, potentially impacting performance as server-side MVC actions tend to be time-consuming. While this approach may work, it underutilizes the benefits of a client-side MVC framework like Angular.

Option #2

Utilize an Angular service to retrieve a GUID from the backend using code similar to the example below:

 ViewBag.reference = Guid.NewGuid().ToString().Substring(0, 6);

If feasible, consider employing WebAPI for small requests and then updating the view with the retrieved GUID using Angular.

It's advisable to determine if generating a random unique number through JavaScript could serve your purpose instead of relying on a GUID. Depending on your specific requirements, either Option #1 or Option #2 can be implemented.

Edit: If you've attempted Option #2 already, then Option #1 becomes the recommended course of action.

Edit 2: To remove a specific element from the cache, you can utilize the following methods:

 $templateCache.remove("<Element Name>");

Alternatively, you can employ:

$cacheFactory.remove("Name")

For further details on the cache factory functionality, refer to: https://docs.angularjs.org/api/ng/service/$cacheFactory

The naming convention typically revolves around the page name, allowing you to inspect the template cache or cache factory object via debugger console for the exact identifier.

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

Upon attempting to fetch input by name, Puppeteer reported the error message: 'Node is not clickable or not an HTMLElement'

This is the structure of my HTML: <div id="divImporte"> <p class="btn01"> <input type="button" name="Enviar Tasas" value="Enviar Tasas"> </p> </div> Here are the diffe ...

Revamp the Twitter button parameters or alter its settings

I'm working on a web page that includes a Twitter button. Before the button, there is an input field and a form where users can easily add relevant hashtags for the page. The goal is to take the text from the input field and populate it in the Twitter ...

Oops! Looks like there was a syntax error with the JSON data at position 1. This resulted in a 400

Having issues submitting form data in my Vue app with an express backend API. The endpoint works fine on postman but I keep getting errors like "SyntaxError: Unexpected token g in JSON at position 0" or "400: Bad Request." I've tried using JSON.parse ...

Exploring the process of passing an array as a function argument from PHP to JavaScript

I am looking for assistance in passing an array as a function argument from PHP to JS. The values I need are retrieved from a database. while ($rows = pg_fetch_array($qry)) { ?> <option value="<?php echo $rows[&ap ...

Mocking objects in unit test cases to simulate real-life scenarios and test the

How do I pass a mocked event object and ensure it is validated? onCallFunction() { const eventValue = event; if (!eventValue.relatedTarget || !eventValue.relatedTarget.last.contain('value')) { super.onCallFuncti ...

What could be causing jQuery animate to malfunction on mobile devices when a viewport is present?

Everything seems to be working fine on my desktop webpage, but when I try it on mobile, there is no scroll... $("HTML, BODY").animate({ scrollTop: 500 }, 1000); This post suggests that mobile devices may not scroll on the body, but on the vi ...

Experiencing difficulties when uploading information to an API in a React JS application

Trying to Send Data via React to Contact Form API Having issues trying to send input data through the API when clicking submit button. The error encountered is that the API call should look like this Example Link However, it calls in a different way Diff ...

Ways to update a div periodically with new data fetched from a file - Here's How!

I am looking to auto-refresh a specific div every few seconds on my index.php page below. <?php session_start(); if (! check_write()) { redirect('testlogin.php'); return; } if (file_exists('lmt.json')) { $lmt = json_de ...

What is the process for reporting a security vulnerability in an npm package if you are the maintainer and publisher?

If I discover a security flaw in my published packages, how can I indicate which versions are vulnerable so that users running `npm audit` will be alerted? ...

What are the common causes of server response issues in AJAX?

I have created a Facebook app that utilizes ajax requests and responses every 3 seconds. The app also has menu items that load content in the main div. All ajax requests are directed to a common.php file. However, some ajax requests are slower than others. ...

How can I use React to switch the visibility of a nested component from the parent container component?

Objective I am in the process of replicating a List Control Component using React and Redux, following the guidelines outlined in Google Material Design layout. This list control will enable users to create, rename, and delete items within the list witho ...

Challenges arising with the express search feature

Currently, I am in the process of developing an API for a to-do application. I have successfully implemented the four basic functions required, but I am facing some challenges with integrating a search function. Initially, the search function worked as exp ...

What is the way to execute a function *once* all my ajax call functions have finished?

I am utilizing jQuery to execute some ajax requests: var information = {}; function process_information(item){ information[item.id] = item; } function perform(){ var calls = []; for(var i = 0; i < 10; i++){ var call = $.get(URL, ...

Making sure to correctly implement email input fields in HTML5: Surprising behaviors observed with the email input type in the Chrome browser

Within the upcoming code snippet, a basic email validation is implemented. An input field's background color will display as white for valid emails and yellow for incorrect values. This functionality operates seamlessly in Firefox; however, in Chrome, ...

The functions getFiles and getFolders will consistently retrieve a single file or folder each time they are

When attempting to fetch all files and folders from my Google Drive, the function .getFiles() is only returning one file, while .getFolders() is only returning a single folder. However, I can confirm that there are multiple folders and files in my drive. ...

Windows authentication login only appears in Chrome after opening the developer tools

My current issue involves a React app that needs to authenticate against a windows auth server. To achieve this, I'm hitting an endpoint to fetch user details with the credentials included in the header. As per my understanding, this should trigger th ...

Encountered an issue with the property 'push' not being defined

Here's the schema for my mongoose model in JavaScript: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const CartSchema = new Schema({ userID: String, items: [{ itemID: String, quantity: Number }] }); modul ...

Using headers in the fetch api results in a 405 Method Not Allowed error

I am facing an issue while attempting to make an ajax request using fetch. The response I receive is a 405 (Method Not Allowed) error. Here is how I am trying to execute it: fetch(url, { method: 'get', headers: { 'Game-Toke ...

"Get Recommendations for Slug Name" API Request in AngularJS and Express Application

One feature I want to implement in my app is the ability for users to set the slug name (URL) for documents, while also ensuring that there is control in place to prevent users from overriding each other. To achieve this, I have decided to create a separat ...

Creating a POP UP feature using Angular and Node was a challenging yet rewarding task

Could someone share with me how to create a pop-up feature using Angular and Node.js? I would like the login page to pop up when the user clicks on the login button. Thank you! ...