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.

3
  • If you want to get an mvc object in jquery, use '@Model.pageChanged' Commented Aug 25, 2017 at 12:50
  • if (@Html.Raw(Json.Encode(@Model.pageChanged )) == true) { ... } (or just if (@Html.Raw(Json.Encode(@Model.pageChanged))) { ... } Commented Aug 25, 2017 at 12:53
  • @StephenMuecke Thank you. It works! Commented Aug 25, 2017 at 12:59

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. It solved it, but why there must be the <text> </text> marks? Without them it didn´t work.
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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.