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);
value; var e = $("#" + "@ViewBag.CC"). val(); var c = "@ViewBag.CC"; var d = $("@ViewBag.CC"). value; var e = $("@ViewBag.CC"). val();
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.
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.
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.
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);
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With