ASP.NET Core MVC Interview Question #157

How can AJAX be used with an ASP.NET Core MVC application?

Testing, AJAX/JavaScript Integration, Localization & Advanced MVC Senior Advanced

Quick Interview Answer

AJAX allows browser JavaScript to send HTTP requests without performing a full-page navigation. An MVC action can return JSON, HTML fragments, status codes, or other content that JavaScript uses to update part of the page.

Detailed Explanation

AJAX allows browser JavaScript to send HTTP requests without performing a full-page navigation. An MVC action can return JSON, HTML fragments, status codes, or other content that JavaScript uses to update part of the page.

The server must apply the same validation, authorization, and security rules to AJAX requests as to ordinary requests. AJAX is a client interaction technique, not a security boundary.

Code Example

const response = await fetch('/Products/Search?term=phone');

if (!response.ok)
    throw new Error('Request failed');

const html = await response.text();
document.querySelector('#results').innerHTML = html;