Using C# Razor Pages to send checkbox values via AJAX requests

In my model class, I have the following:

public class DataModel
{   
    public bool Display { get; set; }
}

After deserializing a FormData object to a JSON object, I am posting the value from a checkbox like this:

this.FormToJSON = form => {
    const json = {};

    new FormData(form).forEach((value, key) => {
      // Ignore the Anti-Forgery Token
      if (key !== "__RequestVerificationToken") {
        json[key] = value;
      }
    });

    return json;
}

The handler in the page is as follows:

public IActionResult OnPostSave([FromBody] DataModel model)
{
    // Do some stuff
}

Even though the Display property is bound to a checkbox input, attempting to deserialize its value of "true" results in the model parameter being null.

A simple fix for this would be:

json[key] = JSON.parse(value);

However, submitting a text field with a value of "true" converts it to a boolean, which is not desired.

Is there a more effective way to handle this? I prefer using AJAX for all requests to handle responses on the front end without relying on jQuery.

Answer №1

Using C# Razor Pages to send checkbox values via AJAX

If you prefer, utilize data: $('#idForm').serialize(),

@Html.AntiForgeryToken()
<form id="idForm"> 
 <input asp-for="Display"  />
         
 <input type="submit" value="submit" id="sub" />
</form>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {    
        // this is the id of the form
        $("#idForm").submit(function (e) {
           e.preventDefault(); // avoid to execute the actual submit of the form.

           
            $.ajax({
                type: "POST",
                url: "/checkboxvalue?handler=Save",
                data: $('#idForm').serialize(),
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
               
                success: function (data) {
                    alert("success"); // show response 
                },
                failure: function (response) {
                    alert(response);
                }
            });

        });
        });
</script>

Ensure to remove the usage of [FromBody]

public IActionResult OnPostSave(DataModel model)
{
    // Perform necessary operations
}

Add the following code in the pagemodel section:

 public bool Display { get; set; }

Answer №2

Success! I finally got it to function!

Currently, I am transforming the form into a request in this way

fetch(pageHandlerURL, {
  method: "POST",
  body: new URLSearchParams(new FormData(formElement))
}).then(response => {
  // handle response
});

Furthermore, on my page handler, I have made slight adjustments as shown below

public IActionResult OnPostSave([FromForm] DataModel model)
{
    // Perform necessary actions
}

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

What are some effective ways to integrate the WordPress API with ReactJS?

Wordpress recently introduced an API that allows you to make HTTP requests without worrying about routes, as the backend is handled for you. I'm curious, how can I integrate ReactJs with Wordpress API? This has been a frustrating challenge for me be ...

When Django comments go wrong: Issues with Ajax and CSRF verification

Having an issue here that seems a bit different from what others have encountered. I've gone through various answers but still no luck. Appreciate any assistance: I've got a list of News items resembling a Facebook feed, and each one has a comme ...

What is the best way to hide the input field when there are multiple parent classes present?

I am currently implementing dynamic fields with jQuery and everything is functioning correctly. The problem arises when I attempt to remove these fields. After searching on Google and browsing past questions on StackOverflow, I noticed that everyone seems ...

C# and json.net provide the ability to selectively deserialize JSON data. This feature

I have come across an issue while working with an API that returns JSON responses. The problem lies in the way they handle error messages, for example: ["501","Invalid apikey"] Instead of the standard JSON response format like: public class AvailableIte ...

Why is the refresh endpoint generating new tokens when an outdated refresh token is used?

Greetings! I am currently utilizing two npm libraries, namely bcrypt and jsonwebtoken. I have implemented an endpoint called /refresh-token wherein I aim to generate a new set of access and refresh tokens. The process involves sending the refresh token to ...

What is the code to convert data to base64 in Javascript when it is not a string?

I am in the process of transferring functionality from an Objective-C iPhone application to a JavaScript iPhone application (using Appcelerator Titanium). In my Objective-C code, I have an NSData object that represents a specific token: //NSData object sh ...

Ensuring Uniform Data Types Across Objects (Using Typescript)

After much trial and error, I have finally reached this point where everything seems to be working perfectly. function test<types extends Record<string,any>>(dict: dictionary<types>){} type dictionary<types extends Record<string, a ...

Learn the process of utilizing AJAX to upload files in CodeIgniter

I have reviewed several solutions How to upload files using ajax in codeigniter File uploads in codeigniter through ajax but none seem to work with my specific code. I am trying to implement a feature where users can upload various types of files (such ...

Debouncing in AngularJS with $watch

In my code, I have an HTML search field represented by the following: <input ng-model-options="{ debounce: 500 }" type="text" ng-model="name"> Along with the JavaScript snippet: $scope.$watch('name', function(newVal, oldVal) { ...

Controller Addition Error

I am currently delving into the world of MVC web application development and facing a challenge. After adding my model and DbContext class, I attempted to include a controller using Entity Framework but encountered an error. Unable to cast object of type ...

selecting a number at random from a defined array

I am looking to generate a series of lottery numbers like the following: my list could be between 1 - 100, or it might range from 1 - 200, or even 1 - 300 select 35 random numbers from the chosen list. choose another set of 25 numbers from the list. pic ...

Having trouble with Jquery and closures or function references?

It seems like the issue is related to a function running in a different scope where the jQuery library is not accessible. This can be seen when the function is called as the last parameter on the second line below. var funcExpandHeight = container.animate ...

Struggling to locate __proto__ of the global object known as "window."

Currently I am using Google Chrome browser. console.log(window.__proto__.__proto__.__proto__); console.log(window.__proto__.__proto__.__proto__ === EventTarget.prototype); The first code mentioned above returns EventTarget.prototype for me. This can be ...

A guide on retrieving values from programmatically created input elements in Java

Here's the HTML code that I am currently working with: <form method="get" action="#" id="startForm"> <input type="text" name="period" id="period" placeholder="The number of days"/> <input type="submit" name="submit" value="subm ...

Switching up the content of an HTML page with JavaScript or JQuery: what you need

Is it possible to update HTML content using JavaScript or JQuery? https://i.sstatic.net/EWOXg.png I am trying to change the contents from 1 to 5 in a sequential order based on the time shown in the image. How can I achieve this using JavaScript or JQuery ...

Tips for designing a pre-selection process

I've been considering the idea of implementing a temporary screen that allows users to choose between different options before proceeding to a specific page. For instance, on the contact page, users would be prompted with a question like "Are you loo ...

Strategies for deactivating the next button when the input field is blank

I have been working on creating a multiple login form and everything was going well, but I am stuck on how to disable the next button if the email input is empty. The input has a class of "email" and the button has a class of "btn-next." Any assistance w ...

Performing a consistent influx of data into a MySQL database using Node.js encounters an issue: "Unable to enqueue Handshake as a Handshake has

I am trying to insert values into a database in a continuous manner. Here is the code I have attempted: var mysql = require("mysql"); const random = require("random"); var con = mysql.createConnection({ host: "xxx", user: "xxx", password: "xxx", ...

Utilizing AngualarJS to bind data to intricate objects using the $resource functionality

Currently, I am working on a restful service that retrieves an order along with a list of items. In my project, I am developing a screen where users can edit specific items within the order. To achieve this, I need to display the list of items before locat ...

Troubleshooting Alignment Problem of Maximize and Close Icons in RadWindow Using ASP.Net

Currently, I am utilizing telerik radwindow to showcase a PDF document. The window seems to be functioning correctly, but there is an issue with the alignment of the maximize and close icons. Ideally, they should appear in the same row, however, they are b ...