Search code examples
javascriptasp.net-mvcviewbag

.Net MVC assigning ViewBag value to JavaScript script variable issue


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.


Solution

  • 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";