繁体   English   中英

插入razor foreach内部的JavaScript对象吗?

[英]Inserting into a JavaScript object inside razor foreach?

当我在局部视图中循环浏览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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM