You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将C#中ViewData的值传递至cshtml并在TypeScript中使用

不用DOM元素传递ViewData值到TypeScript的几种方案

我给你整理了几个实用的方案,不用创建隐藏div就能把ViewData里的temp值传给TypeScript,都是项目里常用的:

方案1:注入全局JavaScript变量

直接在cshtml里输出一个全局变量,TypeScript可以直接引用。这种方式最适合简单的字符串值:

在你的cshtml文件里(比如靠近页面底部或者<head>里)添加这段脚本:

<script>
    // 把ViewData的值挂载到window对象上,成为全局变量
    window.tempValue = '@ViewData["temp"]';
</script>

然后在TypeScript文件里,先声明这个全局变量的类型,之后就能直接使用了:

// 声明全局变量的类型,避免TypeScript报错
declare const tempValue: string;

// 直接使用
console.log(tempValue); // 输出 "abc"

如果你的temp是复杂对象(比如类实例),可以用ASP.NET的Json.Serialize来序列化,避免手动拼接字符串的麻烦:

<script>
    window.tempValue = @Json.Serialize(ViewData["temp"]);
</script>

方案2:用@section组织配置脚本

如果需要传递多个配置项,推荐用这种方式,把配置集中放在脚本块里,代码更整洁:

在cshtml里添加一个Scripts区块(如果你的布局页已经定义了这个区块的话):

@section Scripts {
    <script>
        window.appConfig = {
            temp: '@ViewData["temp"]',
            // 可以添加其他配置项
            otherValue: '@ViewData["other"]'
        };
    </script>
}

然后在TypeScript里定义对应的接口并声明全局变量:

interface AppConfig {
    temp: string;
    otherValue?: string;
}

declare const appConfig: AppConfig;

// 使用配置
console.log(appConfig.temp);

方案3:通过TypeScript模块导入(进阶)

如果你的项目用了模块系统,可以把配置作为一个单独的脚本模块输出。比如在cshtml里创建一个动态的TypeScript文件(或者直接输出模块代码):

<script type="module">
    export const temp = '@ViewData["temp"]';
</script>

然后在你的TypeScript文件里导入这个模块:

import { temp } from './your-cshtml-page'; // 注意路径要对应

console.log(temp);

不过这种方式需要确保你的环境支持模块导入,而且路径要正确,适合现代前端项目。

注意事项

  • 如果temp的值包含特殊字符(比如引号、换行),一定要用Json.Serialize来处理,它会自动转义这些字符,避免破坏JavaScript语法,同时也能预防XSS攻击。
  • 全局变量尽量用独特的命名(比如加上你的项目前缀),避免和其他脚本的变量冲突。

内容的提问来源于stack exchange,提问作者RichaS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:27:46