Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get to Model or Viewbag Variables in a Script Tag

Tags:

Vs'12 asp.net C# MVC4 - Int.Appl.Template EF Code First

Here is my very simple Script

<script class="TractsScript">       $('#Add').click(function (e) {           var val = @ViewBag.ForSection;          alert(val);       }); </script> 

As per example I am wanting to simply set a variable in my script or USE a Viewbag. or Model.

I haven't been able to find an answer in any of the following forums: StckTrace1,StackTraceBetterAnswer

Other Things i have tried:

var model = @Html.Raw(Json.Encode(Model)) alert(model.Sections); alert(@ViewBag.ForSection); 
like image 417
Don Thomas Boyle Avatar asked Sep 18 '13 12:09

Don Thomas Boyle


People also ask

How do you get the ViewBag value in a screenplay?

value; var e = $("#" + "@ViewBag.CC"). val(); var c = "@ViewBag.CC"; var d = $("@ViewBag.CC"). value; var e = $("@ViewBag.CC"). val();

How do I get the ViewBag value in HTML?

The ViewBag object value will be set inside Controller and then the value of the ViewBag object will be accessed in the cshtml file (View) using Razor syntax in ASP.Net MVC Razor. In this article I will explain with an example, how to access value of ViewBag object in cshtml file (View) in ASP.Net MVC Razor.

How do I get ViewBag data on my controller?

To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.

Can we access ViewBag in jquery?

ViewBag is created on Server Side of the Web application and hence it is not possible to directly set it on Client Side using JavaScript or jQuery.


2 Answers

What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.

var val = '@ViewBag.ForSection'; 

If it's an integer you need to parse it as one i.e.

var val = parseInt(@ViewBag.ForSection); 
like image 53
James Avatar answered Oct 25 '22 06:10

James


You can do this way, providing Json or Any other variable:

1) For exemple, in the controller, you can use Json.NET to provide Json to the ViewBag:

ViewBag.Number = 10; ViewBag.FooObj = JsonConvert.SerializeObject(new Foo { Text = "Im a foo." }); 

2) In the View, put the script like this at the bottom of the page.

<script type="text/javascript">     var number = parseInt(@ViewBag.Number); //Accessing the number from the ViewBag     alert("Number is: " + number);     var model = @Html.Raw(@ViewBag.FooObj); //Accessing the Json Object from ViewBag     alert("Text is: " + model.Text); </script>  
like image 22
Fals Avatar answered Oct 25 '22 07:10

Fals