Javascript 从javascript在ViewBag中存储一个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6192950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:40:06  来源:igfitidea点击:

Store a value in ViewBag from javascript

javascriptasp.net-mvc-3viewbag

提问by iLemming

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

如何在 ViewBag 中存储一个值并从 javascript 访问它?

回答by Darin Dimitrov

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:

您不能通过 javascript 在 ViewBag 中存储值。ViewBag 是服务器端的概念,只存在于服务器端。Javascript 在客户端上运行。至于将 ViewBag 中的一些数据存储到 javascript 变量中,您可以使用以下内容:

<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:

既然如此,我总是建议人们不要在 ASP.NET MVC 中使用 ViewBag/ViewData。我推荐使用强类型视图和视图模型。所以你的代码看起来像这样:

@model MyViewModel
<script type="text/javascript">
    var foo = @Html.Raw(Json.Encode(Model))
</script>

回答by Vilx-

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

你不能。ViewBag 是服务器端的东西,Javascript 在客户端运行。