如何使用JS函数在我的视图中显示ViewBag的值? [英] How to display value of a ViewBag in my view with a JS function?
问题描述
我想在使用Java的视图中显示ViewBag中的数据.这是我的代码.
I want to display the data from a ViewBag in my View with Javascript. Here is my code.
查看
<span id='test'></span>
JavaScript
Javascript
function myFunction()
{
$('#test').text('@ViewBag.Test');
}
当调用myFunction()
时,我得到的是文本@ViewBag.Test
,但不是他的值.我该如何解决?
When myFunction()
is called I get the text @ViewBag.Test
but not his value. How can I fix this ?
推荐答案
您需要将采用@ViewBag.Test
值的JavaScript放置在由Razor视图引擎解释的页面中.我的猜测是目前并非如此.
You need to place your JavaScript which takes the @ViewBag.Test
value in a page which is interpreted by the Razor view engine. My guess is that this is currently not the case.
如果要将javascript代码库与视图分开(这是完全合理的),则可以使用全局变量:
If you want to keep your javascript codebase separate from the view (which is entirely reasonable) you can use a global variable:
// in the view:
var testText = '@ViewBag.Test';
// in external js
function myFunction() {
$('#test').text(window.testText);
}
或者,您可以使用data-*
属性:
Alternatively, you can use a data-*
attribute:
<span id='test' data-text="@ViewBag.Test"></span>
// in external js
function myFunction() {
$('#test').text(function() {
return $(this).data('text');
});
}
这篇关于如何使用JS函数在我的视图中显示ViewBag的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!