.Net MVC assigns ViewBag value to JavaScript script variable

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();
    }

      

In 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 the HTML element on my view.

Why is it selecting an item in my view and not returning a string in response? This is really strange behavior.

+3


source to share


3 answers


You are outputting the viewbag value directly to javascript without a quote, so it is not a string in javascript. The html generated from the server looked like this:

var tab = EarnMoney;

      

and since there is a dom element with that id, it selects that element instead of



Put your ViewBag output in a quote like this:

var tab = "@ViewBag.TabVal";

      

+4


source


var tab = @ViewBag.TabVal;

      

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

var tab = EarnMoney;

      



and hence the value will be what the JavaScript engine sees in the variable / property EarnMoney

.

You need to put quotes around whatever is substituted in the literal string:

var tab = "@ViewBag.TabVal";

      

+5


source


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

var tab = '@ViewBag.TabVal';

      

+1


source







All Articles