Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate Razor variable in javascript

I need to evaluate a razor variable inside a JavaScript function. Given the following code:

 @{var unseenNotificationsExist = false;}
 
 @foreach(var notification in viewModel)
 {
    if (notification.WasSeen == false)
    {
      unseenNotificationsExist = true;
      break;
    }
 }

I need to evaluate the unseenNotificationsExist variable in JavaScript like this:

 if(@unseenNotificationsExist == true)
        $('#unseenNotifCount').addClass('notifNotSeen');

However, when I debug the JavaScript code, I get this:

if(True == true)

and also I get the following error:

Uncaught ReferenceError True is not defined

like image 922
Octavian Epure Avatar asked Feb 15 '23 15:02

Octavian Epure


2 Answers

var unseenNotificationsExist = @(unseenNotificationsExist?"true":"false") ;
//the line above must be part of your view

if(unseenNotificationsExist === true)
        $('#unseenNotifCount').addClass('notifNotSeen');
//this can be part of your js file or alternatively and less 
//preferably part of your view
like image 157
Parv Sharma Avatar answered Feb 18 '23 09:02

Parv Sharma


I found a workaround: I added this

var True = true

Now, in javascript there is a variable "True" defined and the evaluation comes down to True == true, which returns true.

like image 37
Octavian Epure Avatar answered Feb 18 '23 11:02

Octavian Epure