从JavaScript在ViewBag存储值 [英] Store a value in ViewBag from javascript
问题描述
我怎么能存储在ViewBag从JavaScript访问它的值?
How can I store a value in the ViewBag accessing it from javascript?
推荐答案
您可以不是一个值ViewBag从JavaScript存储。 ViewBag是一个服务器端的概念,只存在于服务器上。的Javascript运行在客户端上。至于从ViewBag一些数据存储到一个javascript变量而言,你可以使用下列内容:
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>
现在这是说我总是建议人们反对ASP.NET MVC使用ViewBag / ViewData的。我建议使用强类型的视图,视图模型。所以,你的code将是这样的:
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>
这篇关于从JavaScript在ViewBag存储值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!