javascript 在 JS 文件中访问 ViewBag - Asp.net MVC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15636256/
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
Access ViewBag in JS file - Asp.net MVC
提问by KCS Nirav
I have one Viewbag. I have fill that viewbag value from server side in Action result method. I need to access this Viewbag value in Js file. I have access this Viewbag in *.cshl page properly. Here below shown my sample code,
我有一个 Viewbag。我已经在 Action result 方法中从服务器端填充了那个 viewbag 值。我需要在 Js 文件中访问这个 Viewbag 值。我可以在 *.cshl 页面中正确访问此 Viewbag。下面显示了我的示例代码,
Var objMode = '@ViewBag.Mode';
//Written in *.cshtml page.
Var objMode = '@ViewBag.Mode';
//写在*.cshtml页面中。
but i need to access this value like above syntax in *.js file.
但我需要在 *.js 文件中像上面的语法一样访问这个值。
Thanks, Nirav Parikh
谢谢,尼拉夫帕里克
回答by karaxuna
You can't. You can write ViewBag
value in hidden input and then read it from js file:
你不能。您可以ViewBag
在隐藏输入中写入值,然后从 js 文件中读取它:
<input type="hidden" value="@ViewBag.Mode" id="mode" />
JS file:
JS文件:
var mode = document.getElementById('mode').value;
EDIT: Another option:
编辑:另一种选择:
<script src="..." type="text/javascript" onload="InitMyScript('@ViewBag.Mode')"></script>
JS file:
JS文件:
function InitMyScript(mode){
//other code here
}
回答by Kna?is
You can't reference ViewBag or other context items in included script files because those are served as static files and not processed on the server (if you need, this can be worked around by serving a View with the content type of JavaScript).
您不能在包含的脚本文件中引用 ViewBag 或其他上下文项,因为它们作为静态文件提供而不在服务器上处理(如果需要,可以通过提供内容类型为 JavaScript 的视图来解决此问题)。
You need to put the value in your view as JS variable:
您需要将该值作为 JS 变量放入您的视图中:
<script type="text/javascript">
// the object is only required if you want a nice syntax for multiple values.
if (!window.ViewBag) window.ViewBag = {};
window.ViewBag.Mode = @Html.Raw(Json.Encode(this.ViewBag.Mode));
</script>
Now you can reference it in your script file.
现在您可以在脚本文件中引用它。