4

i'm new in C# asp.net mvc. I'm making a ViewBag that contains Dictionary data type in controller and i want to get and display the value by javascript in .cshtml to code it with googlemaps function.

here's my dictionary & viewbag code from the controller:

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

ViewBag.getAlamatVehicle = alamatVehicleMarker;

can you help me how to get the ViewBag.getAlamatVehicle in and how to loop through it please

EDITED

i've tried this :

<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>

but inside the if function it's give a error said that : The name 'id' does not exist in the current context

Shasapo
  • 183
  • 2
  • 15
  • Are you just asking how to loop over a dictionary? A casual Google search immediately found this: http://stackoverflow.com/questions/141088/what-is-the-best-way-to-iterate-over-a-dictionary-in-c – David Aug 12 '16 at 10:11
  • @David i'm sorry i mean i need to loop it in javascript because i want to use it in google maps function, i've edited my question i'm sorry – Shasapo Aug 12 '16 at 10:21
  • @Shasapo Please try my answer and see if it works or not. – Aung Myo Linn Aug 12 '16 at 12:23
  • @kolunar yes i've tried it too and it works :D thank you so much for your solution and answer :D i really appreciate it – Shasapo Aug 12 '16 at 23:25

3 Answers3

4

Something like this would work just be careful of the datatypes, put this in the cshtml.

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

Resources:

Html Raw

Json Encode

Jonathan Newton
  • 832
  • 6
  • 18
2

Here's how I convert VeiwBag into javascript's ViewBag object

<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>

Result:

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"
    }
}

Console:

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

Here's how you can implement the function:

function GetViewBagDictionary(id) {
    if (ViewBag.getAlamatVehicle.hasOwnProperty(id))
        return ViewBag.getAlamatVehicle[id];
    return "not found";
}
console.log(GetViewBagDictionary("v2"));

Console:

Jakarta

Test:

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

Console:

not found
Aung Myo Linn
  • 2,820
  • 3
  • 27
  • 38
1

Please try foreach loop in javascript.

         function GetViewBagDictionary() {

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


            }

sample screen

  • hi ponmani i've tried your answer but help me pls, i've got another problem, please check my edited question – Shasapo Aug 12 '16 at 11:35
  • hi @shaspo ..what is going to do in if loop ? wats the purpose – Ponmani Chinnaswamy Aug 12 '16 at 12:03
  • @Shasapo.. check this link. which may be helpfule for u..http://stackoverflow.com/questions/706603/the-name-controlname-does-not-exist-in-the-current-context – Ponmani Chinnaswamy Aug 12 '16 at 12:07
  • in my google maps function it's only have the id : v1/v2/v3/v4/v5. and i want to get the address value(Bali/Bandung/Jakarta) in dictionary, by comparing the id and the key from dictionary. and if it's not in the dictionary i want it to return "not found" – Shasapo Aug 12 '16 at 12:11
  • @Shasapo.. That is issue while using foreach . try for loop. refer linkhttp://stackoverflow.com/questions/5830549/mvc-iterating-a-viewbag-array-in-javascript – Ponmani Chinnaswamy Aug 12 '16 at 12:45
  • thankyou for your answer and solution for my question :D i've tried the last link you gave me and it's similar from J newton answer :D – Shasapo Aug 12 '16 at 23:21