开发者

Store a value in ViewBag from javascript

How can I store a开发者_C百科 value in the ViewBag accessing it from 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>

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜