Implement an Ajax handler in your Razor page

While I have experience with the customary MyPage.cshtml and MyPage.cshtml.cs files containing OnGetAsync and OnPostAsync methods, I am curious about how to incorporate an additional handler into the model page that can be invoked using JavaScript without the need for a complete form submission. Can anyone provide guidance on this?

Answer №1

using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Mvc;

namespace MyApp.Pages;

public class ListModel : PageModel
{
    private readonly IAntiforgery _antiForgery;

    public AntiforgeryTokenSet AntiForgeryToken {get; private set;}

    public ListModel(
        IAntiforgery antiForgery
    )
    {
        this._antiForgery = antiForgery;
    }

    public async Task OnGet()
    {
        AntiForgeryToken = _antiForgery.GetAndStoreTokens(HttpContext);
    }

    public async Task<JsonResult> OnPostWafflesAsync(bool test)
    {
        System.Console.WriteLine("Test approval result="+test);
        return new JsonResult(new {
            received = true,
            test,
        });
    }
}
<script>
const formData = new FormData();
formData.append('test', false);
fetch(
    `${window.location}?handler=Waffles`,
    {
        method: "POST",
        headers: {
            RequestVerificationToken:`@Model.AntiForgeryToken.RequestToken`,
        },
        body: formData,
});
</script>

In this scenario, we are sending a JsonResult for easier consumption by JavaScript, although the example does not utilize the result.

Please note that in the script referenced above, the handler is Waffles and not OnPostWafflesAsync, related

References:

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

Challenges in Producing a Dynamic Table from a Pre-existing Table

Could you please review This Demo Fiddle and provide guidance on how to append values from selected row(s) by checkbox in a table to a new dynamic table? Here is what I have attempted: var td1 = []; $('#btn').on('click', function () { ...

Challenges faced during the implementation of a personalized transport system in Sentry

Struggling to set up a custom transport for my react app within a UWP container. The fetch API in the UWP environment isn't cooperating with sending events to Sentry, which I discovered after a lengthy debugging session. It appears that the fetch API ...

Is there a way to stop a setTimeout function in React before it is triggered?

In my application, I have set up a functionality where pressing a button starts the clock countdown. If no action is taken within 23 seconds (23000), the state changes to "this.state.user". This part is working correctly. However, if you click on the elem ...

combine array elements with corresponding timestamps

I am working with an array of objects that contain timestamps, as shown below. While I have no issues rendering it in React, I am struggling to figure out how to group and sort the data effectively. const data = [ { id: 0, timeStamp: 1619627889000, title: ...

Identify when objects in kineticJS are dropped

Key Concept Designing a match-the-following activity where red dots can be dragged to blue dots on the left. The draggable red dots must accurately match with the blue target dots. Objective Assigning values to each dot, and ensuring that once a red do ...

Effective File Matching: How to Target Specific File Extensions While Excluding Others

Incorporated into the grunt-aws-s3 task, I created the code snippet below. var weekCache = 'css|js'; var yearCache = 'jpg|jpeg|png|gif|ico|eot|otf|ttf|woff|woff2'; var prodFiles = [ {expand: true, cwd: 'public', src: [&a ...

Deliver JSX components that match one or more keys in the array of strings

Seeking assistance and guidance here. It seems like I might be overlooking something obvious. I am attempting to create a component that accepts either a string or string Array string[] as a property. const ComponentThatReturnsElement = (someElementName) = ...

javascript code to sort an array of objects within a nested array

I need assistance with removing the deleted status from the children key in a nested array of objects using JavaScript. Currently, when I try to filter out the deleted status, I receive an error stating "cannot return filter of undefined." The goal is to ...

changing up the format of nested blockquotes

My website includes various text features, which means that nested blockquotes are a possibility. I am now curious if it is feasible to style nested blockquotes differently from each other! blockquote{ background-color:#666; color:#fff; border ...

Ways to access a conditional rendered ref element in Vue using v-if

I have a specific element that is conditionally rendered using v-if="isLogged" when a user is logged in: <div v-if="isLogged" class="chatBlock" ref="chat" ></div> The issue I'm facing is trying to retrieve the scroll height of the ...

Is there a way I can incorporate v-for with a computed variable?

I am trying to display navigation items based on my authority and other conditions. Below is the code I am using: <template v-for="(subItem, index2) in item.children"> <v-list-item sub-group link :to="subItem.link" exact ...

Set a variable to a specific cell within a table

I've been attempting to insert images into a table and have had success so far - clicking cycles through the available options. However, I've encountered an issue where the counter is not cell-specific but rather global. Is there a way to create ...

Obtaining numerous values through PHP with the help of jQuery and Ajax

Here is the jQuery code I'm using to implement a 'Live Search' feature: $(document).ready(function(){ /* LIVE SEARCH CODE - START HERE*/ var UserID = ('<?php echo $_SESSION['UserID'] ?>'); $(document).ready(functi ...

Adding a CSS class dynamically to a table cell in the backend using Vb.net

Currently, the layout of my table looks like this: <tr> <td> Field1 </td> <td> Field2 </td> <td> Field3 </td> <td> Field4 </td> <td> Field5 </td> </tr> <tr> & ...

What is the correct way to define a variable in Jade?

My app functionality includes exporting user information once they are signed in, allowing the router to update the profile template. However, I am looking to enhance this by dynamically rendering different navigation bars based on the user's sign-in ...

JQuery validation for phone number format 01x-xxxxxxxx

Currently, I am using jQuery Validate to validate the form. In order to validate the phone number field, I have implemented the following code: The phone number should be written in the format 01x-xxxxxxxx var phonereg = /^[0-9]{3}\-[0-9]{7}$/; H ...

Looking to pre-load an image before making a getJson call?

I need help with adding a preloading image effect to my getJson call for drop downs using AJAX. Any suggestions? Here is the code snippet I am currently working with: $.getJSON("myAction.do?method=fetchThruAJAX", { TypeNo: $("#Type").val(), ajax ...

Having issues with Bootstrap affix functionality malfunctioning

I recently put together documentation using the CSS and JavaScript from Bootstrap docs. Here is a snippet of the sidebar code in my documentation: <div class="col-md-3 docs"> <div class="bs-docs-sidebar"> <ul class="nav docs-sid ...

What is the best location to store common utility functions that will be utilized by various Vue.js components?

Typically, I create functions within the component that will use them. However, I am finding that I need to use a particular function in multiple components now. Currently, I would have to duplicate and paste the function into each component, which is not ...

The action of Array.splice unexpectedly changes numerous values, despite being designed to replace just one

My journey to learn coding led me to create my own small idle-clicker-RPG in Javascript and HTML. Currently, I am facing a challenge with my Inventory management codes. Instead of removing and adding items 1:1, it duplicates them when they share the same & ...