Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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.

like image 922
Novice Avatar asked Dec 19 '22 02:12

Novice


1 Answers

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";
like image 191
Phuong Nguyen Avatar answered Dec 24 '22 00:12

Phuong Nguyen