Nate Pet
Nate Pet

Reputation: 46222

MVC null ViewBag in JQuery

I have a ViewBag that has no value. I am not even defining the ViewBag.SelectVale in my controller so I would expect it to be a null value.

When I do the following in JQuery but does not work:

    if ('@ViewBag.SelectVale' == null){ 

     // do something

     }

What works instead is something like:

    if ('@ViewBag.SelectVale' == ""){ 

     // do something

     }

Upvotes: 2

Views: 6972

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156524

In the .NET framework null gets output as an empty string, so if you look at the actual javascript being sent to the browser, in the first case it will say:

if ('' == null)

... and in the second case it will say:

if ('' == "")

Most javascript programmers would tell you to just change your statement to:

if ('@ViewBag.SelectVale')

... because empty strings evaluate to false when they are treated as boolean values in javascript.

Or, since there doesn't appear to be anything really dynamic happening here, try this:

@if(ViewBag.SelectVale == null) {
    <text>
        // do something in javascript.
    </text>
}

... which will avoid even outputting the "do something" javascript since you know when you are rendering the page that SelectVale is null.

Upvotes: 11

Related Questions