The MVC execution sequence: Controller initialization happening after Ajax call

I'm struggling to understand the execution order in MVC architecture.

In my code, I am overriding initialization in the following way:

public class HomeController: Controller {

    protected override void Initialize(RequestContext requestContext)
    { 
       var myVar = "AValue";
       // running some internal security initialization
    }

Then, I have a series of 10 Ajax calls with deferred promises in my javascript.

Setting them up and running onload with $when function.

Now, in a different location than before:

JavaScript file snippet:

this.BeginMyAjaxQuery = function() {
   methodName: MyAjaxQuery
};

In an entirely different Controller that inherits from my HomeController:

public JsonResult MyAjaxQuery()
{           
     return Perform(() =>
     { 
        return ThisQueryWithMyParameter(AValue); 
     });
 }

"Perform" is a wrapper successfully used to create JsonResults.

The issue lies in the behavior of MVC architecture - when I load the URL, the AJAX calls run all the way through on their own thread before my HomeController initialization is complete. As a result, my variables are not set properly leading to incorrect results, although inconsistently.

How is it possible for the ajax calls to bypass my controller initialization and directly access controller methods?

Adding the same code to a constructor in my HomeController also gives erratic results, adding to my confusion.

Additional info mentioned: Using Partial Views & KnockoutJS for front end delivery.

Answer №1

Dealing with the 'staic' Problem

It seems that you are encountering an issue with a static element in your code. While using static variables can make them accessible from anywhere, it also means that they are only initialized once and retain the same value across all threads.

Imagine having only one instance of an object stored in memory. Any changes made to it will affect all threads sharing that object. This aspect should be taken into consideration when dealing with static elements like a 'Security User' object.

public class HomeController : Controller {

    // Note: 'static' ensures that 'new' is called only once
    static SecurityUser = new SecurityUser();

    protected override void Initialize(RequestContext requestContext)
    {
        // Changes made here affect all threads since there's only one SecurityUser object in memory

        // Shared across all threads
        SecurityUser.Ip = "127.0.0.2";
    }


Understanding the MVC Pipeline

A pipeline in computing refers to a series of data processing elements interconnected, where the output of one becomes the input of the next. In the context of MVC (Model-View-Controller) architecture, this concept involves the flow of data and actions during request processing.

Resources such as Wikipedia provide clear definitions of pipelines and their significance in computing. It outlines the progression of data through various processing stages.

The MVC pipeline includes components like AuthenticationFilters, AuthorizationFilters, and ActionFilters which execute specific tasks related to authentication and authorization for invoked ActionMethods.

By utilizing these filters, you can segregate authentication logic, enhancing code maintainability and adhering to good Object-Oriented principles. This approach allows you to define security measures in a single place and reuse them effortlessly.

You may employ this technique to initialize objects implementing a common interface like ISecurity, containing properties such as IP address, username, and admin privileges. These objects can be populated within an action filter and resolved using dependency injection during each HTTP call, streamlining the process effectively.

Source: MSDN

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

Transforming a set of datetime objects into a specific JSON structure

I am currently utilizing a specific JavaScript Calendar tool to display days with scheduled events. The format this calendar tool requires for data input is as follows: { "2019": { "7": { "2": [ {} ], "13": [ {} ...

Exploring a Collection in Meteor: Working with an Object

This issue has been plaguing me for some time now, and it's starting to really get on my nerves. To put it simply: How can we iterate over an object within a collection in a template? Each entry in the collection typically looks like this: { "_i ...

`Connected circles forming a series in d3`

I am currently working on developing an application where the circles are positioned such that they touch each other's edges. One of the challenges I am facing is with the calculation for the cx function. .attr("cx", function(d, i) { return (i * 5 ...

Troubleshooting NodeJS CORS issue with heavy requests for file uploads

I'm currently working on a project that involves an Angular front end and a NodeJS API deployed in production using AWS services like S3 and Elastic Beanstalk. When attempting to upload images, I encounter a CORS error if the image is too large or wh ...

Building upon the foundation of .NET Core MVC, developers can successfully implement AJAX functionality

When I send my data from the frontend to a backend controller using ajax, I expect the controller to create a model and redirect to a new view with that model. However, the redirection never occurs. Is it possible to perform a redirect inside the controlle ...

What sets apart a React component from a function-as-component in React?

React is really confusing to me right now. Take this simple react component for example: export default function Foo(){ return( <div> <div>some text</div> </div> ) } I want to add a child compone ...

How can I use JavaScript to modify the style of the first unordered list (ul) element without affecting the

function displayMenu(){ var parentElement = document.getElementById("menuItem1"); var lis = parentElement.getElementsByTagName("ul"); for (var i = 0; i < lis.length; i++) { lis[i].setAttribute("style","display: block"); } } When the button is clicke ...

What is the best way to use jQuery to set the height of one div equal to another div

Edited: I am facing a situation with a 3-column layout - Column A, Column B, Column C. The height of Column A is dynamic and I need to set the same height for both Column B and C. For instance, Column A contains a tabbed panel with varying heights based ...

What are some ways to reuse an angular component multiple times?

I am utilizing an angular component to dynamically load charts into my widget: Below is an example of the component: angular.module("generalApp").component("chartPie", { template: "<div class=Pie></div>", bindings: { data: "=", }, control ...

When clicking on column headers, a DataGrid housed within an UpdatePanel triggers a full refresh

Recently, I encountered an issue with a DataGrid on an asp.net webforms page within an unconditional UpdatePanel: <asp:UpdatePanel ID="upData" runat="server">. During the data binding process inside the protected override void OnLoadComplete(EventAr ...

What is the correct way to invoke a function from a different file?

Having trouble calling a function from another file in my JS code. I am unable to call a function from another js file. I suspect there is an issue with linking the two files. Code snippet from my first JS file const { response } = require('expre ...

Using jQuery/Javascript to create a dynamic content slider

I am currently working on developing a straightforward content slider. When the page loads, my goal is to display only one item (including an image and some content) and provide a navigation system for users to move through the items. Below is the basic H ...

Show only future events using JavaScript and XML

I am facing a challenge with an interactive map that showcases event dates in various regions of the United States. While the map successfully extracts data from an XML document and displays it, I am encountering an issue where events from 2014 are not bei ...

Issues with hover styles and transitions not being correctly applied to newly appended elements in Firefox

Utilizing an SVG as an interactive floor plan, I have implemented a feature where hovering over different areas on the floor plan (<g> elements) causes them to expand and float above other areas. The element scaling is triggered by CSS, but I use jQu ...

Transform strings in a table into integers within a specified scope

My World.json file is quite large and contains extensive data on countries worldwide. I've been utilizing a list to display this data in a table format, with the intention of sorting all values accordingly. However, I have encountered an issue - all m ...

Exploring the differences between selecting an element by its class and making multiple calls to select elements

I have a question about choosing multiple elements from a page. Is it better to use a selector by class, or make multiple calls using the selector by id? The number of elements I want to select, or unwanted elements that need to be checked by the selector ...

Exclude a particular row from a table when there is no identifier

My PHP code generates a basic table. <table border="1" id="control> <tbody> <tr>...</tr> <tr>...</tr> <tr>...</tr> //Row #3 <tr>...</tr> <tr>... ...

Firefox having trouble loading ThreeJS

My current project involves showcasing 3D files online using ThreeJS. While it operates smoothly on Chrome and MS Edge, I encountered a hitch on Firefox: Uncaught TypeError: Error resolving module specifier “three”. Relative module specifiers must star ...

Having trouble displaying child nodes in MatTreeView with Angular 14?

In an Angular project, I am attempting to display a private group's data from GitLab (utilizing a public one for testing purposes). To achieve this, I have implemented the NestedTreeView component. While the parent nodes are displaying correctly, I am ...

Trapped in the clutches of the 'Access-Control-Allow-Origin' snag in our Node.js application

Our nodeJS application is deployed on AWS Lambda, and we are encountering an authentication issue with CORS policy when trying to make a request. The error in the console states: Access to XMLHttpRequest at 'https://vklut41ib9.execute-api.ap-south-1 ...