How to send ViewData as a boolean in the MVC framework

Is there a way to pass boolean values from a controller to a view using ViewData and retrieve it as a boolean value in JavaScript?

Controller:

ViewData["isLogged"] = true;

View

<script type="text/javascript">
var isLogged = <%= (bool)ViewData["IsLogged"] %>;   /// attempting this throws a JavaScript error
</script>

I can always do this instead:

<script type="text/javascript">
var isLogged = '<%= ViewData["IsLogged"] %>';   /// now isLogged is a string 'True'
</script>

However, I prefer to keep the isLogged object as a boolean rather than a string if possible.

Answer №1

Simply eliminate the use of quotation marks.

<script type="text/javascript>
    var isLoggedIn = <%= (bool)ViewData["Login"] ? "true" : "false" %>;
</script>

After this modification:

var isLoggedIn = true;

This code will then be interpreted as a boolean by the web browser.

Answer №2

In my opinion, you might want to try the following:

<script type="text/javascript>
    var isLoggedIn = new Boolean(<%= (bool)ViewData["IsLoggedIn"] ? "true" : "false" %>);
</script>

Update: It seems that the initial approach I suggested would not be effective. To make it work, the true/false values passed to Boolean() must be in lowercase characters.

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

Do we need to have the 'input type file' field as

I am currently working on a PHP form that includes mandatory fields for saving the data. For example: <td><input class="text_area required" type="text" name="new field" This form also has Javascript code with file upload functionality, which I ...

Developing a single page that caters to various users' needs

Greetings to all my friends, As a front end developer, I am in the process of implementing a dashboard for a project that involves different users with varying permissions. Each user should only have access to certain parts of the page, resulting in some ...

Step by step guide on turning off email verification during user registration in MVC ASP Identity

Is there a way to bypass the email confirmation process for user account creation in MVC asp.net identity 2.0? ...

Tips for centering or aligning a component to the right using Material UI?

Is there an efficient method to align my button to the right of its parent in Material UI? One approach could be using: <Grid container justify="flex-end"> However, this would also require implementing another <Grid item />, which m ...

Building a Multiple Choice Text Box with HTML

I am looking to create a section on my website where I can display text, and I have 9 buttons on the page that I want to stay within the same page without redirecting. The goal is for the text to update based on which button is clicked, with a fading ani ...

Struggling to effectively utilize filter() to eliminate an element from the DOM

Encountering some challenges when trying to target the correct element from the DOM following a successful ajax call. This is my current view setup: @foreach($tags as $tag) <div class="skillLabel deleteSkill"> <h4> ...

Encountering a problem when attempting to delete a record in an ASP.Net website with Entity Framework

I recently started learning how to use Entity Framework in asp.net with Visual Studio 2012. I followed a helpful tutorial on this link. After creating the grid and running the website, everything seems to be working fine except for the delete operation. W ...

Allowing only certain URLs to be opened in a new tab using regular expressions

I am currently developing a website that requires sanitizing the output from the database while allowing certain HTML tags. To achieve this, Regex is being used for data sanitization. Currently, the system permits standard Google (normal href with no ...

Replacing multiple attributes within a complex HTML opening tag using Node.js regular expressions

I'm currently working on a Node.js project where we need to search through several PHP view files and replace certain attributes. My goal is to extract the values of HTML open tag attributes and replace them. To clarify, I want to capture anything in ...

Tips on executing a $.get request while submitting a form?

Instead of using AJAX to submit my form, I am trying to implement a progress bar by making GET requests to the server while the form is submitting. This is particularly important when dealing with multiple file uploads that may cause the submission to take ...

Is it necessary for the Jquery Component to return false?

I'm currently working on developing a jQuery module using BDD (Behavior-driven development). Below is the code snippet for my component: (function($) { function MyModule(element){ return false; } $.fn.myModule = function ...

Modify the div class depending on the date

I am in the process of creating a simple webpage where I can keep track of all my pending assignments for college. Take a look at the code snippet below: <div class="assignment"> <div class="itemt green">DUE: 28/03/2014</div> </d ...

Step-by-step guide on inserting a div element or hotspot within a 360 panorama image using three.js

As I work on creating a virtual tour using 360 images, I am looking to include hotspots or div elements within the image that can be clicked. How can I store data in my database from the event values such as angle value, event.clientX, and event.clientY wh ...

Using JQuery to make an AJAX request with URL Rest path parameters

Currently, I have a REST service located at /users/{userId}/orders/{orderId} and I am looking to make a call to it using JQuery. Instead of simply concatenating the IDs like this: $.get( 'users/' + 1234 + '/orders/' + 9876, fu ...

When clicking on a link in React, initiate the download of a text file

Usually, I can use the following line to initiate the download of files: <a href={require("../path/to/file.pdf")} download="myFile">Download file</a> However, when dealing with plain text files like a .txt file, clicking on ...

What steps should I follow to enable a tooltip in this specific situation using qtip?

In my database, I have tables for venues, venue types, and map icons with the following relationships: A venue belongs to a venue type A venue type belongs to a map icon Each venue result is shown on the index page as a partial. Each partial ...

Error in template loading

Currently, I am going through the Angular.js tutorial to learn how to incorporate some of its advanced features into my existing applications. Everything has been smooth sailing until I reached the (angular route) section. Unfortunately, I've hit a ro ...

The code functions properly when run locally, however, it encounters issues when deployed

When testing the following lambda code locally using Alex-app-server, everything works perfectly fine. However, when I publish it and test on AWS Lambda, it gets stuck within the else statement. It prints the console log 'OUT PUBLISH' but doesn&a ...

Firestore query is not displaying the expected data, resulting in an empty array being returned

I've encountered an issue where my query is returning an empty array. Despite double-checking for errors and typos in the query, no error messages are popping up. This problem arose while working on a learning project inspired by Firehip's NextJS ...

Unlocking the power of React using TypeScript for optimal event typing

I need assistance with properly typing events in TypeScript. Consider the following function: import * as React from 'react'; someHandler = (event: React.SyntheticEvent<HTMLInputElement> | React.KeyboardEvent<HTMLInputElement>) =&g ...