ASP.NET Core MVC Interview Question #158

How can an MVC action return a partial view for an AJAX request?

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

Quick Interview Answer

An action can prepare a ViewModel and return PartialView with the partial view name and model. Browser JavaScript can request the action and place the returned HTML into a selected DOM element.

Detailed Explanation

An action can prepare a ViewModel and return PartialView with the partial view name and model. Browser JavaScript can request the action and place the returned HTML into a selected DOM element.

This approach keeps HTML rendering on the server and can be convenient for server-rendered applications that need small dynamic regions without building a separate client-side application.

Code Example

[HttpGet]
public async Task<IActionResult> Search(string term)
{
    var model = await _service.SearchAsync(term);

    return PartialView(
        "_ProductResults",
        model);
}