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

Simple Way to Modify Color of Active Page Link - HTML, CSS, and JavaScript

I found a helpful example on how to change link colors for the current page here. Here is the script I added: <script> // current page highlight $(document).ready(function() { $("[href]").each(function() { if (this.href == window.l ...

Node Webkit: No visible content?

Recently, I decided to explore Node-Webkit and encountered an issue. Despite coding the script below, nothing seems to appear on the screen and the file I intended to create remains missing. Even after installing npm for fs and os modules, I still face no ...

The cause of Interface A improperly extending Interface B errors in Typescript

Why does extending an interface by adding more properties make it non-assignable to a function accepting the base interface type? Shouldn't the overriding interface always have the properties that the function expects from the Base interface type? Th ...

Utilizing jquery.load to fill out a form following unsuccessful validation with ajax in CodeIgniter

After exploring numerous form validation tutorials that utilize jQuery Ajax, I have observed a common trend - they all focus on successful form validation. However, my quest is to uncover the process of displaying errors when server-side validation fails. ...

How to Target HTML Tags Locally using CSS Modules in Next.js?

I am looking to implement smooth scrolling specifically on one page in my Next.js application, such as my blog. Instead of applying it to the entire site through the globals.css file, I need a way to inject scroll-behavior: smooth; into the html tag only f ...

The variable from AJAX is not being displayed in PHP

Need help with transferring a JavaScript variable to the same PHP page. The following code is what I have so far: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script& ...

How can I extract data from [Object object] in Node.js?

Can someone help me figure out how to extract data from [Object object]? Let's consider the following scenario for clarity. // Fetching data using dirty method var info = database.get('/htmltest') // Contents of test.db file {"key":"foo", ...

Encountering a TypeError while trying to run Pythonshell on my Mac device

When I run a python script in node.js using python shell, it works perfectly on my Windows system. However, I encounter an error when trying to run the same thing on my Macbook: Error: TypeError: can't multiply sequence by non-int of type 'float ...

How can I add text to a textbox within a duplicated div using Javascript or Jquery?

I'm looking to add text to a cloned div's text box using jQuery. I have a div with a button and text box, and by cloning it, I want to dynamically insert text into the new div. $(document).ready(function () { $("#click").click(function () { ...

Check for the presence of an Outlook add-in within a web application

I'm having trouble determining whether my hosted web application is being accessed through a browser or from within the Outlook 2013/2016 client. I have developed a web application that offers different functionalities depending on whether it is acce ...

Tips for excluding specific codes from running in BeforeAll for a specific Describe() block in Jasmine

Currently, I am in the process of writing a Jasmine unit test spec. The JS file contains several describe() blocks. Within the BeforeAll function, my objective is to execute a function only for the "A" and "C" Describe-Blocks. How can this be accomplished ...

Easily validating forms using javascript

I'm attempting to design a basic HTML form and would like to implement javascript for validating the input values. Below is the form tag: <form action="" onSubmit="return formValidation();" method="Post" name="form"> Here is a section of the ...

Having difficulties updating a value in Angular through a function written in HTML- it refuses to update

<select ng-model="currentTimeStartHour" style="width: 33%" ng-change="UpdateTime(this)"> <option ng-repeat="hour in choices" value="{{hour.id}}">{{hour.name}}</option> </select> Somewhere else on the page... {{totalHours}} Whe ...

Tips on adding line breaks after periods that are not at the end of a sentence in HTML text nodes with regular expressions

Looking to craft a regex that can identify all periods not enclosed in quotes and not followed by a '<'. This is for the purpose of converting text into ssml (Speech Synthesis Markup Language). The regex will be utilized to automatically inse ...

Updating the value of a MongoDB item two days after its creation

I've been working on a NodeJS application that stores form data in a MongoDB database collection. My goal is to implement a function that can modify certain values of the object in the database collection 48 hours after the form data is initially save ...

What is the best way to access the second item using getByRole in React Testing Library when there is no specific name?

I am familiar with using the name option to select the first item here, but how can I go about selecting the second item if it does not have a name identified? -------------------------------------------------- button: Enter "Go": ...

Generate an array using the properties of an object

Seeking a more efficient way to configure settings for an app using objects? Consider starting with the following object: var obj = { property_one: 3; property_two: 2; property_three: 1; } And transforming it into the desired array format: v ...

Locate the child element that has a particular class assigned to it

I need help writing a code to search through all children elements in order to find a div with a specific class. Unfortunately, the DIV I am looking for does not have an ID. Below is the sample HTML that I will be working with: <div class="outerBUB ...

Setting the state based on Promise values within a loop

I am currently facing a challenge in my React project where I am using axios to interact with an external API. The goal is to loop through the array of objects retrieved from the API call and utilize the values returned by a separate function within the ...

What is the process of incorporating HTML into a jQuery program in order to immerse the world in an element?

I am looking to utilize HTML with the value in a checkbox, After adding a shortcode: <label class="HCheck">(this is val 1 )</label> and incorporating jQuery to change it to: <label class="HCheck">(this is val 1 ) ...