2

I have jQuery function in my view.

And variable in my view model:

public bool pageChanged { get; set; }

Function:

$(document).ready(function () {
    if (@Model.pageChanged == true) {
        $('html, body').animate({
                scrollTop: $("#picture_section").offset().top
        }, 2000);
    }
});

Without if statement it works fine. But if I want to compare bool value of my model it doesn't work. I tried alert("@Model.pageChanged") and it showed right value.

So I tried

if(@Model.pageChanged) {
}

if(@Model.pageChanged == true) {
}

But it didn't work. How could I change the if statement to work? Is there problems with types?

Thank you for solving issue.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Michal Fiala
  • 21
  • 1
  • 8

2 Answers2

3

So there are boundaries between the client and server that are potentially in play. The model code within a view, in the context you have it, essentially determines what gets rendered to the view. So if you have this:

if (@Model.pageChanged == true) {

The server-side code renders the value of pageChanged to the client, except I found there are issues with rendering false. A common workaround was:

if (@Model.pageChanged.ToString().ToLower() == true) {

Which will render:

if (true == true) {

OR

if (false == true) {

So you don't necessarily need the "== true" part.

If you want to control what JS actually gets rendered, you can do:

$(document).ready(function () {
    @if (Model.pageChanged == true) {
        <text>
         $('html, body').animate({
            scrollTop: $("#picture_section").offset().top
         }, 2000);
        </text>
    }
});

This text:

@if (Model.pageChanged == true) {

Becomes a server-side evaluation and determines whether the jQuery animate statement event renders at all, based on the value of pageChanged.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
0

Or you could do something like this:

if ("@Model.pageChanged" == "True") {...}

Here is the link to explain why "True" not "true": Why does Boolean.ToString output "True" and not "true"

oopsdazie
  • 716
  • 1
  • 7
  • 22