How can I store a value in the ViewBag accessing it from javascript?
If you want the previous view bag data to be posted, keep that in a hidden form field. After user submit's the form, It will print " From GET-Totally new value "; Try to avoid dynamic stuff like ViewBag/ViewData for transferring data between your action methods and views.
The ViewBag object value will be set inside Controller and then the value of the ViewBag object will be accessed inside JavaScript function using Razor syntax in ASP.Net MVC Razor.
In Controller's Action Method in order to assign the Model data to ViewBag object we assign as shown below. In the below syntax, I am using employee object as well as a list of employee objects to store the data in ViewBag object and return ViewBag to the View or . cshtml and bind it to the HTML table.
The Controller consists of two Action methods. Inside this Action method, the value of the Name is set in a ViewBag object which will be later set in the Hidden Field created using Html. Hidden helper function. Inside this Action method, the value of the Hidden Field created using the Html.
You cannot store a value in ViewBag from javascript. ViewBag is a server side concept and exists only on the server. Javascript runs on the client. As far as storing some data from ViewBag into a javascript variable is concerned you could use the following:
<script type="text/javascript">
var foo = @Html.Raw(Json.Encode(ViewBag.FooBar))
</script>
Now this being said I always advice people against using ViewBag/ViewData in ASP.NET MVC. I recommend using strongly typed view and view models. So your code will look like this:
@model MyViewModel
<script type="text/javascript">
var foo = @Html.Raw(Json.Encode(Model))
</script>
You can't. ViewBag is a server-side thing, Javascript runs on client side.
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