Sending dynamic boolean model property via AJAX dynamically

I am facing an issue while passing a property from my model to an AJAX form. The boolean value is resolving as "true/false" and causing problems in the process.

$.ajax({
    url: '/Projects/SearchTable2',
    type: "GET",
    data: {
        sub_num: @Model.SubmissionNumber,
        read_only: @Model.ReadOnly,
    }
});

Model.ReadOnly is resolving to either true or false, leading to an error

Uncaught ReferenceError: False is not defined
upon execution of the code. Is there any workaround for this issue? Or perhaps another method to pass the variable to the Controller method?

Answer №1

@Model.ReadOnly is displayed as a Capital Boolean (True), however JavaScript does not recognize it, so you need to modify your code as follows:

$.ajax({
    url: '/Projects/SearchTable2',
    type: "GET",
    data: {
        sub_num: @Model.SubmissionNumber,
        read_only: @Model.ReadOnly.ToString().toLowerCase(),
    }
});

Answer №2

When the razor engine runs the code within the view, it will display the following code on the browser:

read_only: True,

If @Model.ReadOnly returns a boolean true.

In C#, a boolean value is either True or False, whereas in JavaScript, it is lowercase true or false.

Therefore, when the JavaScript framework of the browser tries to execute this code, it doesn't recognize True as true. Instead, it interprets 'True' as a JavaScript variable which leads to the "True is not defined" error since we haven't declared it earlier!

To resolve this issue, you need to convert the boolean value generated by the C# code into something recognizable by JavaScript. Simply call ToString() and then ToLower() to change True to true

$.ajax({
    url: '/Projects/SearchTable2',
    type: "GET",
    data: {
        sub_num: @Model.SubmissionNumber,
        read_only: @Model.ReadOnly.ToString().ToLower(),
    }
});

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

Enhance chat functionality by integrating MySQL database to store and update chat messages

I'm currently working on developing a chat system that allows users to enter the chat and send messages. The messages are being stored in a MySQL database, and here is a snippet of my code... <script> $('input[type=text]').on('ke ...

The trio of Javascript, Ajax, and FormData are

I'm struggling with sending form values to a PHP file. Here's the code I have: <form role="form" id="upload_form" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="formlabel">Title< ...

PWA JavaScript struggling with GPS geolocation coordinates

I am experiencing issues with the GPS coordinates being stuck when using geolocation in a Progressive Web App (PWA). Sometimes, the coordinates get stuck at the previous location, even if the user has moved since then. I suspect that this is due to the GP ...

Box Pattern with Pop-Up Modal

Check out the grid of squares I've coded below: <div class='square-container'> <div class='square'></div> <div class='square'></div> <div class='square'></div& ...

Executing a python function utilizing dojo/request

Being a beginner in the field of web development, I apologize if my question seems basic. I am attempting to utilize python for handling AJAX requests. Although the documentation suggests that Dojo/request can assist me with this task, I have struggled to ...

How can I modify the color of a div when a validation error occurs?

I have recently completed a contact form with validation using the constraint validation api. Although the files are functioning as intended, I am curious if there is a method to make the error boxes turn red when an error occurs and white (or hidden) when ...

What drawbacks should be considered when utilizing meteor.js for development?

After viewing the meteor.js screencast, I was truly impressed by its seamless web application development capabilities, especially in terms of live updates and database synchronization. However, I am curious about its scalability once the website goes live ...

Perform calculations for product and sum when button is clicked

I received the following task for an assignment: Develop 3 functions along with a form. The first function should execute upon button press and utilize the other 2 functions. These two functions are supposed to compute the sum of two numbers and the ...

Determining the size of an image prior to uploading it in a React

The solution for this issue can be found using vanilla JavaScript here To clarify, instead of using alert(), my goal is to store the dimensions in the state object. How can I adapt this code into a React component utilizing the OnChange() event handler? ...

Retrieve the URL redirected by JavaScript without altering the current page using Selenium

Is there a way to extract the URL I am supposed to be redirected to upon clicking a button on a website, without actually being redirected? The button triggers a complex Javascript function and is not a simple hyperlink. click() method doesn't meet my ...

Why is it that PowerShell cannot execute Angular commands?

Recently, I started diving into Angular and encountered an issue using PowerShell in Windows. Every time I run an angular command like: ng new new-app or ng serve I keep getting this error message: ng : File C:\Users\< username >\ ...

Custom server not required for optional dynamic routes in NextJS version 9.5.2

I am attempting to implement localized routes with an optional first parameter in the form of /lang?/../../, all without requiring a custom server. Starting from NextJS version 9.5, there is a new dynamic optional parameters feature that can be set up by c ...

There are encountered issues with the `POST` value not functioning properly on certain pages

Form submission was done using script: window.document.form_id.submit(); After redirecting to the action link, unable to retrieve value using $_post['name'] This functionality works fine on local environment but not on the server. ...

Best practices for managing Ajax requests in ASP.Net MVC 3

When it comes to implementing Ajax calls in ASP.Net MVC, there are numerous options available for making calls, handling them on the server, and managing success and error scenarios on the client side. While some aspects have clear solutions, I have strugg ...

Just a simple canvas animation

My canvas animation consists of two rectangles moving in different directions, but I believe it can be simplified further. http://jsfiddle.net/tmyie/R5wx8/6/ var canvas = document.getElementById('canvas'), c = canvas.getContext('2d&apo ...

Creating a promise class in JavaScript

I am in the process of creating a simple promise class with chainable .then() functionality in javascript. Here is my progress so far: class APromise { constructor(Fn) { this.value = null; Fn(resolved => { this.value = resolved; }); ...

Tips for creating a tabbed form that easily glides between tabs

After coming across this form design, I am inspired to create something similar with a twist. Instead of having each tab display all content at once, I want the tabs to scroll from right to left, giving it a more animated effect. Can someone offer suggesti ...

Unable to find the specified element within Gmail

Recently, I've been working on a project with Nightwatch.js where it checks the dev environment and sends a test email to a Gmail account. Following that, it logs into Gmail, locates and clicks on the correct email. My main challenge now is trying to ...

What is the process for populating a checkbox with data from a configuration file using JavaScript?

I have a requirement where I need to populate a list of checkboxes with data from a configuration file. To elaborate, if my checkboxes are meant to select sports, within my JSON configuration file I have an array like this: sports: ["Tennis", "Rugby", "S ...

Vue function that inserts <br> tags for addresses

My Vue filter retrieves and combines address details with a , Vue.filter('address', (address, countryNames = []) => { const formattedAddress = [ address?.name, address?.company, address?.add1, address?.add2, address?.town ...