如何使用JS函数在我的视图中显示ViewBag的值? [英] How to display value of a ViewBag in my view with a JS function?

查看:445
本文介绍了如何使用JS函数在我的视图中显示ViewBag的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆