Denis
Denis

Reputation: 13

Use ViewBag object in JQuery, value does not display correctly

I'm working on a MVC3 app. In my action, I have ViewBag object that has either true or false value - I used breakpoint and can see that in the action, they have the correct values. Now, when I get to the view, I want to check these ViewBag object in jQuery Code:

if (@ViewBag.ind == true) {
        $objKpr = $("[email protected]");
        $objKpr.click();
    }

When I tested own code with Firebug, it returned

 if (False == false) 
         {
        $objKpr = $("[email protected]");
        $objKpr.click();
         }

Viewbag was interpreted as a 'False' rather than a variable holding a value of false.Why is this happening?

Thanks for answers But the question was in another-Why a ViewBag inside a jQuery would not yield the correct value?

Upvotes: 1

Views: 1486

Answers (3)

Saranga
Saranga

Reputation: 3228

Try this;

if ("@(ViewBag.ind == null ? "false" : ViewBag.ind.ToString().ToLower())" === "true") {

It will not give errors even if ViewBag.ind is null.

Thanks!

Upvotes: 0

Adrian Thompson Phillips
Adrian Thompson Phillips

Reputation: 7158

Calling @ViewBag.MyProperty in your code will cause the Razor engine to render the property by calling ToString() on the value. E.g.

if (@ViewBag.ind == true) {

Renders as:

if (True == true) {

So you may want to change your code to something like:

if (@ViewBag.ind.ToString().ToLowerInvariant() === true)

Although the values in ViewBag are only available to inject into the JavaScript/View when the page is rendered. They're not as dynamic as JavaScript, where the variables are held client side and can be flipped/changed as many times as you like.

You may wish to use the technique to inject initial values for your scripts:

$(document).ready(function () {
    var ind = @ViewBag.ind.ToString().ToLowerInvariant();

    DoSomething(ind);
});

function DoSomething(ind) {
    if (ind) {
        $objKpr = $("[email protected]");
        $objKpr.click();
    }
}

This way you can initialise the behaviour of ind at render, but then change the value of ind on the client side and call the function DoSomething() many times with different values.

You may wish to look into using JSON, AJAX calls and the JavaScript Module pattern.

Upvotes: 1

Satpal
Satpal

Reputation: 133453

You can simply use

var condition = @(myBooleanVariableInCSharp ? "true" : "false";
if (condition == true) {
    $objKpr = $("[email protected]");
    $objKpr.click();
}

OR

You should use @ViewBag.ind.ToString().ToLower(). You need to convert the value which JavaScript can understand.

Your problem as bool values are lowercase in javascript and uppercase in C#

Like

if (@ViewBag.ind.ToString().ToLower() == true) {
    $objKpr = $("[email protected]");
    $objKpr.click();
}

Upvotes: 1

Related Questions