如何从 JS 访问 ViewBag [英] How do I access ViewBag from JS
本文介绍了如何从 JS 访问 ViewBag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试的方法.
通过浏览器查看 JS,@ViewBag.CC
只是空白...(缺失)
Looking at the JS via browser, the @ViewBag.CC
is just blank... (missing)
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();
推荐答案
如果您使用的是 razor 引擎模板,请执行以下操作
if you are using razor engine template then do the following
在你看来写:
<script> var myJsVariable = '@ViewBag.MyVariable' </script>
更新:更合适的方法是在主布局上定义一组配置,例如基本 url、facebook API Key、Amazon S3 基本 URL 等......```
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 ...```
<head>
<script>
var AppConfig = @Html.Raw(Json.Encode(new {
baseUrl: Url.Content("~"),
fbApi: "get it from db",
awsUrl: "get it from db"
}));
</script>
</head>
你可以在你的 JavaScript 代码中使用它,如下所示:
And you can use it in your JavaScript code as follow:
<script>
myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
alert(myProduct.fullUrl);
</script>
这篇关于如何从 JS 访问 ViewBag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文