5

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

4
  • Are you just asking how to loop over a dictionary? A casual Google search immediately found this: stackoverflow.com/questions/141088/… Commented Aug 12, 2016 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 Commented Aug 12, 2016 at 10:21
  • @Shasapo Please try my answer and see if it works or not. Commented Aug 12, 2016 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 Commented Aug 12, 2016 at 23:25

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

thankyou so much for your answer, i've tried it too and your solution it's works :D
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

6 Comments

hi ponmani i've tried your answer but help me pls, i've got another problem, please check my edited question
hi @shaspo ..what is going to do in if loop ? wats the purpose
@Shasapo.. check this link. which may be helpfule for u..stackoverflow.com/questions/706603/…
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.. That is issue while using foreach . try for loop. refer linkhttp://stackoverflow.com/questions/5830549/mvc-iterating-a-viewbag-array-in-javascript
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.