Octavian Epure
Octavian Epure

Reputation: 1039

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

Upvotes: 4

Views: 7905

Answers (6)

Parv Sharma
Parv Sharma

Reputation: 12705

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

Upvotes: 5

Sajjad Ali Khan
Sajjad Ali Khan

Reputation: 1813

I prefer to use Json.Encode , whenever i want to convert the model data to JSON objects or JSON variables .

For converting an object(dto) of model to javascript

var accountDto = @Html.Raw(Json.Encode(@Model.AccountDto))

For converting a (bool)property of model

var isTrue = @Json.Encode(Model.IsTrue)

Upvotes: 2

Octavian Epure
Octavian Epure

Reputation: 1039

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.

Upvotes: 4

Alex Marculescu
Alex Marculescu

Reputation: 5770

try using

if('@unseenNotificationsExist')

Upvotes: -1

Daniele
Daniele

Reputation: 1938

You tried with:

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

Upvotes: -1

UweB
UweB

Reputation: 4110

If you want to not have the the JavaScript rendered, use Daniele's suggestion.

If you insist on making the comparison in JavaScript:

if(@unseenNotificationsExist.ToString().ToLower() === true)

Upvotes: 0

Related Questions