ASP.NET Core MVC Intermediate

Calling actions from JavaScript with fetch

Sometimes a page should update without a full reload, such as adding to a cart or loading more comments. This lesson calls MVC actions from JavaScript with fetch, sends the anti-forgery token, and chooses between returning JSON and returning a partial view.

Add to cart without reloading
  1. StartButton clickedJavaScript reads the token
  2. Step 2fetch POSTToken in the RequestVerificationToken header
  3. Step 3Action runsValidates token, updates the cart
  4. Step 4Json returned{ count: 3 }
  5. EndPage updatedCart count changed with textContent

Two styles

  • Return JSON and build the HTML in JavaScript: good for small values such as a cart count.
  • Return a partial view and insert the HTML: the markup stays in Razor, with the same tag helpers and encoding as the rest of the page.
  • Both use the same controller actions you already know, with the same validation and authorization.

The action

C#
[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> AddToCart(int productId, CancellationToken ct)
{
    var product = await db.Products.FindAsync([productId], ct);
    if (product is null) return NotFound();

    cart.Add(productId);
    return Json(new { count = cart.Count });
}

public async Task<IActionResult> Comments(int postId, int page)
{
    var comments = await commentService.PageAsync(postId, page);
    return PartialView("_Comments", comments);   // HTML fragment, no layout
}

The JavaScript

The view includes a form with @Html.AntiForgeryToken() (any form with method post does this for you). Read the token and send it as a header, which ASP.NET Core accepts as RequestVerificationToken.

JavaScript
const token = document.querySelector('input[name="__RequestVerificationToken"]').value;

document.querySelectorAll('[data-add-to-cart]').forEach(btn =>
  btn.addEventListener('click', async () => {
    const res = await fetch('/Products/AddToCart', {
      method: 'POST',
      headers: { 'RequestVerificationToken': token,
                 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ productId: btn.dataset.addToCart })
    });
    if (!res.ok) { alert('Could not add the item.'); return; }
    const { count } = await res.json();
    document.querySelector('#cart-count').textContent = count;
  }));

async function loadComments(postId, page) {
  const res = await fetch(`/Posts/Comments?postId=${postId}&page=${page}`);
  document.querySelector('#comments').insertAdjacentHTML('beforeend', await res.text());
}

Good habits

  • Keep the anti-forgery check on every POST, including AJAX ones.
  • Check res.ok and show a friendly error; network calls fail.
  • Insert JSON text with textContent, never innerHTML, to avoid XSS. Partial views are already HTML-encoded by Razor.
  • Make the page work without JavaScript first, then enhance it, so links and forms still work if a script fails.

Interview question

How do you send the anti-forgery token with a fetch POST in ASP.NET Core MVC?

Render the token in the page with a form or @Html.AntiForgeryToken(), read the hidden __RequestVerificationToken input in JavaScript, and send its value in a RequestVerificationToken request header (or as a form field in the body). The [ValidateAntiForgeryToken] attribute then validates it together with the anti-forgery cookie.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.