C# 如何从 JS 访问 ViewBag
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10008023/
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
How do I access ViewBag from JS
提问by Doomsknight
My attempted methods.
我尝试的方法。
Looking at the JS via browser, the @ViewBag.CCis just blank... (missing)
通过浏览器查看 JS,@ViewBag.CC只是空白...(缺失)
var c = "#" + "@ViewBag.CC";
var d = $("#" + "@ViewBag.CC").value;
var e = $("#" + "@ViewBag.CC").val();
var c = "@ViewBag.CC";
var d = $("@ViewBag.CC").value;
var e = $("@ViewBag.CC").val();
采纳答案by amd
if you are using razor engine template then do the following
如果您使用的是剃刀引擎模板,请执行以下操作
in your view write :
在你看来写:
<script> var myJsVariable = '@ViewBag.MyVariable' </script>
UPDATE:A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```
更新:更合适的方法是在主布局上定义一组配置,例如基本 url、facebook API 密钥、Amazon S3 基本 URL 等......```
<head>
<script>
var AppConfig = @Html.Raw(Json.Encode(new {
baseUrl: Url.Content("~"),
fbApi: "get it from db",
awsUrl: "get it from db"
}));
</script>
</head>
And you can use it in your JavaScript code as follow:
你可以在你的 JavaScript 代码中使用它,如下所示:
<script>
myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
alert(myProduct.fullUrl);
</script>
回答by gdoron is supporting Monica
ViewBagis server sidecode.Javascriptis client sidecode.
ViewBag是服务器端代码。Javascript是客户端代码。
You can't reallyconnect them.
你无法真正连接它们。
You can do something like this:
你可以这样做:
var x = $('#' + '@(ViewBag.CC)').val();
But it will get parsed on the server, so you didn't really connect them.
但是它会在服务器上被解析,所以你并没有真正连接它们。
回答by adt
<script type="text/javascript">
$(document).ready(function() {
showWarning('@ViewBag.Message');
});
</script>
You can use ViewBag.PropertyName in javascript like this.
您可以像这样在 javascript 中使用 ViewBag.PropertyName。
回答by ZeNo
try: var cc = @Html.Raw(Json.Encode(ViewBag.CC)
尝试: var cc = @Html.Raw(Json.Encode(ViewBag.CC)
回答by Arsman Ahmad
You can achieve the solution, by doing this:
您可以通过执行以下操作来实现解决方案:
JavaScript:
JavaScript:
var myValue = document.getElementById("@(ViewBag.CC)").value;
or if you want to use jQuery, then:
或者,如果您想使用jQuery,则:
jQuery
jQuery
var myValue = $('#' + '@(ViewBag.CC)').val();

