首页 > 解决方案 > 插入 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>

标签: javascriptasp.net-mvcrazorasp.net-mvc-5

解决方案


尝试这个: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>

推荐阅读