javascript - 插入 razor foreach 内的 JavaScript 对象?
问题描述
当我在局部视图中遍历 C# 列表时,我需要添加到 JavaScript 对象,我尝试过<text></text>
,@:
但它们只是呈现纯 JavaScript 文本,这是完整的局部视图:
@using Resources;
<script>
var resources = {};
@{
Dictionary<string, string> resx = new Dictionary<string, string>();
foreach (var item in typeof(AppResources).GetProperties().Where(p=>p.PropertyType==typeof(string)))
{
resx.Add(item.Name, item.GetValue(item).ToString());
var key = item.Name;
var value = item.GetValue(item).ToString();
@:resources[@key] = @value;
}
}
console.log("resources_BEGIN");
console.log(resources);
console.log("resources_END");
</script>
这是在 HTML 源代码中呈现的:
<script>
var resources = {};
resources[lbAccountSettings] = Account settings;
resources[lbActivate] = Activate;
resources[lbArabicName] = Arabic Name;
resources[lbAreas] = Areas;
console.log("resources_BEGIN");
console.log(resources);
console.log("resources_END");
</script>
解决方案
尝试这个:var jsvariable=@Html.Raw(Json.Encode(<your_charp_variable>))
编辑:
<script>
var resources = {}
@{
Dictionary<string, string> resx = new Dictionary<string, string>();
foreach (var item in typeof(AppResource).GetProperties().Where(p=>p.PropertyType==typeof(string)))
{
resx.Add(item.Key, item.Value);
}
}
resources=@Html.Raw(Json.Encode(resx));
</script>
推荐阅读
- c# - 如何在发布管道中更改 Appsettings 和 Config 信息
- mysql - 查询 COUNT(field) 不考虑 id
- typescript - 设置 tsconfig.json 目标会破坏路径
- android - 如何在 Kotlin 中打开菜单项选择的新页面?
- excel - 在vba中的大写字母前放置一个空格
- database - 有没有办法为 SQL 查询等迭代器优化 Rust 过滤器?
- angular - 如何在另一个formArray中禁用反应式表单控件
- search - 在 MarkLogic java API 中提取属性并获取结果
- php - 将内容从 Drupal 7 迁移到 CSV 或另一个 MySQL 数据库
- c# - C# - 如何使用 ushort 在 byte[] 前添加并通过 TCP 发送