Showing the ViewBag dictionary in JavaScript in ASP.NET MVC is key to enhancing the user

Recently, I started learning C# asp.net mvc and decided to create a ViewBag containing Dictionary data type in the controller. My goal is to retrieve and display the values using JavaScript in .cshtml for implementing Google Maps functionality.

Here is the code snippet of my dictionary and ViewBag 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;

I need assistance in fetching the ViewBag.getAlamatVehicle in .cshtml file and also guidance on how to loop through it.

UPDATE

I attempted the following:

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

However, an error occurs inside the if function stating:

The name 'id' does not exist in the current context

Answer №1

If you're looking for a solution, consider the following advice but make sure to pay attention to data types. Insert this code snippet in the cshtml file.

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

Additional Information:

Learn about Html Raw

Explore Json Encode

Answer №2

This is a method I use to transform ViewBag data into a JavaScript object named ViewBag:

<script type="text/javascript>
var ViewBag = {
    IsDeveloper: ("@ViewBag.IsDeveloper").toLowerCase() === 'true',
    IsUser: ("@ViewBag.IsUser").toLowerCase() === 'true',
    EmptyID: "@ViewBag.EmptyID",
    Users_ID: "@ViewBag.Users_ID",
    Main_Category: "@ViewBag.Main_Category",
    Category_ID: "@ViewBag.Category_ID",
    UserName: "@ViewBag.UserName",
    UserLocation: "@ViewBag.UserLocation",
    UserType: "@ViewBag.UserType",
    getVehicleAddress: { 
        @{
            int count = 0;
            string vehicle_str = "";                
            foreach (var item in ViewBag.getVehicleAddress) 
            {
                vehicle_str += "\"" + item.Key + "\": \"" + item.Value + "\"";
                count++;
                if (count < ViewBag.getVehicleAddress.Count)
                {
                    vehicle_str += ", ";
                }
            }
            var html_data = new HtmlString(vehicle_str);
        }
        @html_data
    }
}
console.log(ViewBag.getVehicleAddress);
</script>

Output:

var ViewBag = {
    IsDeveloper: ("False").toLowerCase() === 'true',
    IsUser: ("True").toLowerCase() === 'true',
    EmptyID: "00000000-0000-0000-0000-000000000000",
    Users_ID: "7e49def2-3887-4149-b419-5f1f51d4ec58",
    Main_Category: "Technology Services",
    Category_ID: "ca9381c7-0379-4a72-80df-270287954164",
    UserName: "John Doe",
    UserLocation: "",
    UserType: "Regular",
    getVehicleAddress: { 
        "v1": "Los Angeles", "c2": "New York", "c3": "Chicago"
    }
}

Console Log:

Object {v1: "Los Angeles", c2: "New York", c3: "Chicago"}

If you need to access the function, here's an example:

function RetrieveFromViewBag(key) {
    if (ViewBag.getVehicleAddress.hasOwnProperty(key))
        return ViewBag.getVehicleAddress[key];
    return "not found";
}
console.log(RetrieveFromViewBag("c2"));

Log Output:

New York

Testing Scenario:

console.log(RetrieveFromViewBag("c4"));

Result in Console:

not found

Answer №3

Experience the power of a foreach loop in JavaScript.

function ExtractViewData() {
    @foreach (let element in ViewData)
    {
        let key = element.key;
        let value = element.value;
    }
}

https://i.sstatic.net/0iIJA.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I encountered a problem with nesting .then functions where I was unable to properly send the response back to the

When working with express.js I have two APIs that serve the same type of data, and I am building a simple application that should first use the primary API. If an error occurs, then it should fall back to the second one. The approach I attempted involves ...

Creating an event listener in the window object for the three.js

Struggling to create a MyObject.prototype.onWindowResize function for scaling a simple cube on window resize. Can't seem to make it work - either getting undefined or no change at all. Spent hours searching for a solution with no luck. Any help would ...

Achieving the value of $IntDir in C#

Although I am aware of $(BaseIntermediateOutputPath), I require the complete path. It is puzzling that Microsoft opted for "$(BaseIntermediateOutputPath)$(ConfigurationName)\" for AnyCPU, however, they went with "$(BaseIntermediateOutputPath)$(Platfo ...

Populating the table with data through a repetitive process

Is there a way to automatically populate a table using values from an array? <table> <thead> <tr> <div ng-repeat="n in range" > <th> {{vm.data.list[n].temp.day}} {{vm.symbal}} ...

I'm having trouble with my Laravel edit page not functioning properly when using vue.js. Can anyone help me troubleshoot

Currently, I am developing a dashboard to display details. Users can click on the edit button to modify their information. However, when I try to edit by clicking the button, nothing happens. It seems like the editing feature is not functioning properly, a ...

What are the strategies for handling various browsers (such as Safari, Chrome, Internet Explorer, and Opera) with Selenium WebDriver? Which libraries are necessary to install for this task?

I am a beginner in the world of selenium webdriver. While I have successfully created tests using the Firefox driver, I am encountering difficulties when trying to work with other web browsers. IWebDriver driver = new FirefoxDriver(); this ...

Error message: Unhandled error: The function Role.Create is not defined

I'm encountering an issue with a ".create is not a function" error while trying to repopulate my database upon restarting nodemon. Previously, everything was functioning well and all the tables were populated successfully. However, I keep receiving th ...

Basic Ajax script fails to function properly

I'm having trouble with the external website that is supposed to output valid JSON data. The code seems too simple for there to be an issue, I've tried using both get and post methods. $(document).ready(function() { $.get("https://www.w3scho ...

A guide on using the patch API and Multer package to update files and images

After reviewing my code, I have successfully created a user model and imported it into the controller. Additionally, I have also imported an upload middleware from another directory where the code is written for uploading files/images using the multer pack ...

What is the best way to retrieve content from a different website using javascript in an asp.net environment?

Currently working on a web application in asp.net where I want to provide users with a JavaScript code that allows them to fetch content from my website and display it on their own website. To handle user requests on my website, I have implemented a gener ...

Error: The `queries` property is undefined and cannot be read (react.js)

Here is the code snippet I am currently working with: import { useState } from 'react' import { QueryClientProvider, QueryClient } from 'react-query' import { ReactQueryDevtools } from 'react-query-devtools' import Navba ...

Tips on modifying the interface based on the selected entry using jQuery

I am attempting to display a text when different options are selected from the dropdown list. Here is the code for the drop-down list: <div class="dropdown"> <select class="form-control" id="ltype" name="ltype"> <option value=""&g ...

Vue.JS behaves differently on Firefox and Safari compared to Chrome and Edge by not hiding the scrollbar

Currently I am dipping my toes into frontend development using Vue.JS and Vuetify. One of my objectives was to hide the scrollbar (even though I know I can't completely delete it). I found a code snippet that should achieve this goal, which is include ...

The occurrence of Multiple Button events leads to an error message stating: "Uncaught TypeError: Cannot read property 'remove' of undefined"

I am struggling to add an EventListener to each Delete Button (1,2,3) as I keep encountering an error that says "add" is undefined. Do you have any suggestions on how to fix this issue? My goal is to display a confirmation window when the DELETE button is ...

Error: NextJS Client-Side Rendering Issue

I find this situation quite perplexing... Everything seems to be working fine except for the onClick code and useEffect code. I attempted running document.querySelector('button'); in the console, but it returned undefined. It appears that JavaSc ...

Sorry, there was an issue connecting to the SQL Server database. Our team is working on resolving the problem

LTL; FTP here. Currently working on an eCommerce site based on Shakeel Osmani's Tutorial here. The issue arises during the registration process for new users on the website, where I encounter a "'System.Web.HttpException' Additional inform ...

Transforming units of time from days, hours, minutes, and seconds into hours, minutes, and seconds

I am using a timesheet application that accurately records the number of hours worked within a specific timeframe. However, I am encountering an issue where the total hours worked are displayed in a format like this after surpassing 24 hours: 1.01:06:16. M ...

How can I use an AngularJS directive to choose a specific item from a list?

Among my plethora of templates, I'm seeking a way to handpick one from the list and transfer its ID to an input field within a form. Here's how my setup appears: <form> <input type="hidden" name="template_id" ng-model="template.temp ...

Cypress: harnessing the power of regular expressions within jQuery selectors for the ":contains()" method

Trying to use Cypress along with a regular expression to target an element that includes specific text. The following get() function successfully works: cy.get('[data-cy=tile]').contains(new RegExp(myVar)) However, the following command does no ...

Using Marionette.js with jQuery to submit a form can cause the disappearance of page data

Currently, I am working on a project that involves a form submission setup where a POST request is made to download a file. Here is how the process is structured: app -> .setHandler 'eventForForm' controller.submitForm() controller -> ...