4

I am trying to send a string value from my controller action on my view using View Bag like this

 public ActionResult Services()
    {

        ViewBag.TabVal = "EarnMoney";
        return View();
    }

On my view I am assigning the View Bag value to a JavaScript variable like this

 @section scripts{

<script>
    var tab = @ViewBag.TabVal;
    console.log(tab);
 </script>
}

on my console I get this value

    <li id="EarnMoney"> EarnMoney</li>

which is an HTML element on my view.

Why is it selecting the element on my view and not giving a string in return ?This is really weird behavior.

1
  • 3
    Do we have all of the code here, cause this wouldn't happen from the code shown... Commented Jul 16, 2015 at 8:50

3 Answers 3

5

You output viewbag value directly to javascript, without the quote, so it's not a string in javascript. Html generated from server looked like this:

var tab = EarnMoney;

and since there's a dom element with that id, it selects that element instead

Put your ViewBag output in quote like this instead:

var tab = "@ViewBag.TabVal";
Sign up to request clarification or add additional context in comments.

Comments

5
var tab = @ViewBag.TabVal;

When the Razor engine renders the view, the @ expression is replaced directly:

var tab = EarnMoney;

and thus the value will be whatever the JavaScript engine sees in the variable/property EarnMoney.

You need to put the quotes in what substituting in a literal string:

var tab = "@ViewBag.TabVal";

3 Comments

I noticed this, but this doesn't explain to me why it would output as HTML in the console
@Coulton it doesn't. I suspect that EarnMoney is defined JS value at that point (eg. the same – missing quotes – defect could appear elsewhere).
Sorry @Richard but EarnMoney is not defined any where as a JS variable ,the ViewBag assignment without quotes always tries to select an element with that id and if the element does not exists in HTML it gives an error,I did not continued the discussion because I thought you guys told me that this is the default behavior.
1

you can get value from view bag by using quote and @ sign

var tab = '@ViewBag.TabVal';

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.