asp.net mvc 显示 ViewBag 字典到 javascript

Posted

技术标签:

【中文标题】asp.net mvc 显示 ViewBag 字典到 javascript【英文标题】:asp.net mvc display ViewBag dictionary to javascript 【发布时间】:2016-12-19 07:34:57 【问题描述】:

我是 C# asp.net mvc 的新手。我正在控制器中制作一个包含 Dictionary 数据类型的 ViewBag,我想通过 .cshtml 中的 javascript 获取并显示该值,以便使用 googlemaps 函数对其进行编码。

这是来自控制器的我的字典和 viewbag 代码:

Dictionary<string, string> alamatVehicleMarker = new Dictionary<string, string>();
alamatVehicleMarker.Add("v1","Bali");
alamatVehicleMarker.Add("v2","Jakarta");
alamatVehicleMarker.Add("v3","Bandung");

ViewBag.getAlamatVehicle = alamatVehicleMarker;

你能帮我如何获取 ViewBag.getAlamatVehicle 以及如何循环访问它

已编辑

我试过了:

<script>
function GetViewBagDictionary(id) 

            @foreach (var item in ViewBag.getAlamatVehicle)
            
                var key = item.Key;
                var Value = item.Value;

                if (key == id)
                
                    return Value;
                
            

            return "not found";
        
<script>

但是在 if 函数内部它给出了一个错误说:The name 'id' does not exist in the current context

【问题讨论】:

你只是在问如何遍历字典吗?随便用谷歌搜索一下就发现了这个:***.com/questions/141088/… @David 对不起,我的意思是我需要在 javascript 中循环它,因为我想在谷歌地图功能中使用它,我已经编辑了我的问题,对不起 @Shasapo 请试试我的答案,看看它是否有效。 @kolunar 是的,我也试过了,它有效:D 非常感谢您的解决方案和回答:D 我真的很感激 【参考方案1】:

这样的东西会起作用注意数据类型,把它放在 cshtml 中。

var dictionary = @Html.Raw(Json.Encode(ViewBag.getAlamatVehicle));
for(var key in dictionary )
    var value = dictionary[key];
    console.log(value);

资源:

Html Raw

Json Encode

【讨论】:

【参考方案2】:

以下是我如何将 VeiwBag 转换为 javascript 的 ViewBag 对象

<script type="text/javascript">
var ViewBag = 
    IsDesigner: ("@ViewBag.IsDesigner").toLowerCase() === 'true',
    IsAdmin: ("@ViewBag.IsAdmin").toLowerCase() === 'true',
    EmptyGuid: "@ViewBag.EmptyGuid",
    Advertisers_ID: "@ViewBag.Advertisers_ID",
    Primary_Category: "@ViewBag.Primary_Category",
    Primary_Category_ID: "@ViewBag.Primary_Category_ID",
    Advertiser_Name: "@ViewBag.Advertiser_Name",
    Advertiser_NameMM: "@ViewBag.Advertiser_NameMM",
    BookTypeName: "@ViewBag.BookTypeName",
    getAlamatVehicle:  
        @
            int marker_count = 0;
            string markers_str = "";                
            foreach (var item in ViewBag.getAlamatVehicle) 
            
                markers_str += "\"" + item.Key + "\": \"" + item.Value + "\"";
                marker_count++;
                if (marker_count < ViewBag.getAlamatVehicle.Count)
                
                    markers_str += ", ";
                
            
            var html_str = new HtmlString(markers_str);
        
        @html_str
    

console.log(ViewBag.getAlamatVehicle);
</script>

结果:

var ViewBag = 
    IsDesigner: ("False").toLowerCase() === 'true',
    IsAdmin: ("True").toLowerCase() === 'true',
    EmptyGuid: "00000000-0000-0000-0000-000000000000",
    Advertisers_ID: "7e49def2-3887-4149-b419-5f1f51d4ec58",
    Primary_Category: "Construction Services",
    Primary_Category_ID: "ca9381c7-0379-4a72-80df-270287954164",
    Advertiser_Name: "Dolphin Ayeyarwady Pile Construction Co., Ltd.",
    Advertiser_NameMM: "",
    BookTypeName: "YD",
    getAlamatVehicle:  
        "v1": "Bali", "v2": "Jakarta", "v3": "Bandung"
    

控制台:

Object v1: "Bali", v2: "Jakarta", v3: "Bandung"

以下是实现该功能的方法:

function GetViewBagDictionary(id) 
    if (ViewBag.getAlamatVehicle.hasOwnProperty(id))
        return ViewBag.getAlamatVehicle[id];
    return "not found";

console.log(GetViewBagDictionary("v2"));

控制台:

Jakarta

测试:

console.log(GetViewBagDictionary("v4"));

控制台:

not found

【讨论】:

非常感谢您的回答,我也试过了,您的解决方案很有效:D【参考方案3】:

请在 javascript 中尝试 foreach 循环。

         function GetViewBagDictionary() 

            @foreach (var item in ViewBag.getAlamatVehicle)
             
                 var key = item.Key;
                 var Value = item.Value;
             


            

【讨论】:

嗨 ponmani 我已经尝试过你的答案,但请帮助我,我还有另一个问题,请检查我编辑的问题 嗨@shaspo .. if 循环会做什么?目的是什么 @Shasapo.. 检查此链接。这可能对你有帮助..***.com/questions/706603/… 在我的谷歌地图功能中,它只有 id:v1/v2/v3/v4/v5。我想通过比较字典中的 id 和键来获取字典中的地址值(Bali/Bandung/Jakarta)。如果它不在字典中,我希望它返回“未找到” @Shasapo.. 这是使用 foreach 时的问题。尝试循环。参考链接http://***.com/questions/5830549/mvc-iterating-a-viewbag-array-in-javascript

以上是关于asp.net mvc 显示 ViewBag 字典到 javascript的主要内容,如果未能解决你的问题,请参考以下文章

ASP.Net MVC的ViewBag一个坑,不要跳进去

在 ASP.NET MVC Core 控制器的构造函数中设置 ViewBag 属性

ASP.NET MVC中的Razor语法

vbscript ASP NET MVC - Pasar un viewbag del controlador a la vista

如何在 ASP.NET MVC 视图中显示 2 个列表

Asp.net mvc基础Controller给View传递数据的方式