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

ESLint warning: Potentially risky assignment of an undetermined data type and hazardous invocation of an undetermined data type value

Review this test code: import { isHtmlLinkDescriptor } from '@remix-run/react/links' import invariant from 'tiny-invariant' import { links } from '~/root' it('should return a rel=stylesheet', () => { const resp ...

Attempting to modify the state within a nested object located in an array by using json data

My objective is to retrieve data from the Google Books API, which returns JSON data in a similar format to what my state displays. I aim to update the title with the title string provided by the JSON data. Currently, I am encountering a "failed to compile" ...

Exploring Rails integration with FullCalendar: Retrieving data from the database using varying column titles

Currently utilizing Rails 4.0 in conjunction with FullCalendar, I am encountering an issue where some fields in my database do not align perfectly with the defaults of FullCalendar. For instance: My columns FullCalendar's Na ...

Getting the href of an element using Selenium in C# when hovering over with the mouse

On a website, you can find profiles listed with their profile photos. https://i.stack.imgur.com/9kH35.jpg I am attempting to retrieve the HREF of these profile photos (not the photo itself, but the profile link). In order to do this, I need to capture the ...

Could a potential concurrency issue arise when handling a Queue in JavaScript?

I am faced with a situation where I need to persist an array of properties via AJAX calls to a database. However, the current API does not allow sending the strings in batches, and simple looping will cause overwriting issues. To overcome this, I have impl ...

Oops! Module './api/routers' not found

Hello, I hope everyone is doing well... Currently, I am working on developing a NextJS single-page web application. To create a custom server for NextJs, I am utilizing Express, MongoDB, and nodemon for hot reload functionality. Upon starting the server, ...

Utilize the power of AJAX for efficiently sorting search results retrieved from MySQL

I'm in the process of designing a flight search page. The initial page contains a form, and when the submit button is clicked, the search results are displayed on the second page. Here's the link to the first page: To test it out, please follow ...

Error: An issue occurred with the tasks in the Gruntfile.js file

pm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74041506001a1106041b0600151834445a445a44">[email protected]</a> No description npm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" ...

Vue js: Automatically assign alternate text to images that are not found

Currently, I am in the process of developing a website that features a variety of products, each with its own unique image. For binding the image URL to the source attribute, I use the following code snippet: <img :src="product.ImageUrl"/> In case ...

Exploring a JavaScript file with the power of JavaScript and HTML

I have a .js file that contains the following data (excerpt for brevity) var albums= "tracks":[ {"title":"Dunnock","mp3":"Birdsong-Dunnock.mp3", "lyrics":"The Dunnock or hedge sparrow has a fast warbling song often delivered from t ...

Retrieving a specific Project ID from Asana Task API using Node.js and parsing the JSON response

Utilizing the Asana Task API, we have the capability to retrieve a task's associated projects along with their GID and Notes (description text). The main objective Our aim is to extract the GID of the project containing #websiteprojecttemplate in its ...

Transform gradient backgrounds as the mouse moves

I'm attempting to create a unique gradient effect based on the cursor position. The code below successfully changes the background color of the document body using $(document.body).css('background','rgb('+rgb.join(',')+&a ...

Unexpected next() error occurred

Currently, I am working on a project using node.js along with express and MongoDB. I have encountered an error that I cannot seem to understand. When I remove the next() function call, everything works perfectly fine. However, when I include next(), it tr ...

Trouble with AJAX call to web service function

i'm facing an issue with my ajax call function findPICKey() { filter = document.getElementById('MainCT_dtvJobVac_PIC').value; $.ajax({ type: 'POST', contentType: 'application/json;&a ...

Verifying StartDate and EndDate using AngularJS and Bootstrap Datepicker

My HTML Coding <form name="myForm"> <div class="row"> <div class="col-md-2"> <input data-ng-model="Data.StartDate" type="text" id="startDate" name="startDate" class="form-control" data-da ...

Customize specific styles for individual divs one at a time (without the use of jQuery)

Can you assist me with this issue? I am trying to display the <span class="badge badge-light"><i class="fa fa-check-circle"></i></span> tag (initially set to "visibility: hidden") when clicking on a div with the class "role-box". He ...

Showing the loading screen while waiting for the static Next.js app to load

Looking for a way to implement a loading screen right before the entire static page finishes loading? I'm currently utilizing modules:export to create my static page, but struggling to listen to the window load event since NextJs has already loaded th ...

The 'data' variable is not defined in the React custom hook Pagination

I am currently working with an API that shows music categories on a browser, and I'm attempting to create a custom pagination hook. However, I keep encountering an error stating "object is not iterable." I am new to custom hooks and would appreciate a ...

Remove Chosen Pictures (Checkbox/PHP/MySQL)

I am currently displaying images from a Database using the following HTML code: <li> <input type="checkbox" id="1" /> <a rel="gallery_group" href="images/big/1.jpg" title="Image 1"> <img src="images/small/1.jpg" alt="" ...

Retrieving data from a remote PHP server using JavaScript

I am currently working on two separate websites. Site A is coded using only HTML and JavaScript, while site B utilizes PHP. I am trying to figure out a way to access variables from site B within site A. For example: The code for site A looks something li ...