Store a value in ViewBag from javascript

◇◆丶佛笑我妖孽 提交于 2019-12-21 07:24:14

问题


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


回答1:


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>



回答2:


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



来源:https://stackoverflow.com/questions/6192950/store-a-value-in-viewbag-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!