Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store a value in ViewBag from javascript

How can I store a value in the ViewBag accessing it from javascript?

like image 674
iLemming Avatar asked May 31 '11 20:05

iLemming


People also ask

How do you keep data in your ViewBag?

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.

Can I access ViewBag from JavaScript?

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.

Can we store object in ViewBag?

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.

How do you store a ViewBag value in a hidden field?

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.


2 Answers

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>
like image 155
Darin Dimitrov Avatar answered Oct 02 '22 10:10

Darin Dimitrov


You can't. ViewBag is a server-side thing, Javascript runs on client side.

like image 30
Vilx- Avatar answered Oct 02 '22 11:10

Vilx-