Raj
Raj

Reputation: 555

How to use @ViewBag value in JQuery

I want to use ViewBag value in JQuery. Does anyone provide me some idea how to do that.

//My code

    <label>Cost<span id="spCost">@ViewBag.Cost</span></label>

//JQuery

var original = $("#spCost").val;

I also tried:

var original = '@ViewBag.Cost';

But, currently, it is showing no value in original.

Please help me.

Upvotes: 2

Views: 610

Answers (2)

sebu
sebu

Reputation: 2954

<script type="text/javascript">
    var val = parseInt(@ViewBag.Cost);
</script> 

Upvotes: 1

ddm310
ddm310

Reputation: 135

At the end of your view, write something similar to this -

<script type="text/javascript">
var original = @ViewBag.Cost;
alert(original);
</script> 

OR

<script type="text/javascript">
var original = @Html.Raw(@ViewBag.Cost); 
alert("Text is: " + original.Text);
</script> 

or if you want to use the viewbag value in a separate .js file, then create a js file something similar to this

var newJSFile = (function(my){
   my.CostFromView = 0;
   //Your code
}(newJSFile || {}));

and then at the end of your view,

<script type="text/javascript">
$(function(){
newJSFile.CostFromView = @ViewBag.Cost;
});
</script> 

Upvotes: 3

Related Questions