The JSON format in ASP.Net Core MVC does not have designated data fields

I am currently facing an issue with my JavaScript code related to cascading dropdowns. The setup involves having one dropdown for selecting a car brand and another dropdown for choosing a specific model under that brand. The functionality should work in such a way that when a brand is selected, the corresponding models should populate the second dropdown. To achieve this, I use a method called GetModelsJson in the controller to fetch the data from Brand and Model tables and return it as JSON.

public JsonResult GetModelsJson(int p)
        {
            var models = (from x in GetModels() 
                          join y in GetBrands() on x.BrandId equals y.Id 
                          where x.BrandId == p
                          select new
                          {
                              Text = x.Name,
                              Value = x.Id.ToString()
                          }).ToList();
            return new JsonResult(new { data = models });
        }

When rendering the view, I utilize the following code:

@Html.Label("Brands")
@Html.DropDownList("drpBrand",Model.BrandList,"--Select Brand--", new {@class = "form-control"})
@Html.Label("Models")
@Html.DropDownList("drpModel",Model.ModelList,"--Select Model--", new {@class = "form-control"})

The problem arises within the JavaScript section where issues occur during a for loop execution. Strangely, the length of the data variable along with its fields like text and value are showing up as undefined.

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
    $(function(){
        $('#drpBrand').change(function(){
            var id = $('#drpBrand').val();
            $.ajax({
                url: '/Admin/Vehicle/GetModelsJson',
                data: {p : id},
                type: "POST",
                dataType: "Json",
                success: function(data){
                    console.log(data);
                    $('#drpModel').empty();
                    for (let i = 0; i < 3; i++){
                        $('#drpModel').append("<option value ='" + data[i].value + "'>" + data[i].text + "</option>");
                    }
                }
            });
        });
    });
</script>

This issue results in the second dropdown for models showing up as empty. Snapshot of the website interface

Despite the console displaying the data fields like "A5", "A4", "A6", the second dropdown remains empty as depicted in the image.

Answer №1

The image you provided shows that the server's object has a field called "data" which contains an array. In order to make adjustments to your code, follow these steps:

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
    $(function(){
        $('#drpBrand').change(function(){
            var id = $('#drpBrand').val();
            $.ajax({
                url: '/Admin/Vehicle/GetModelsJson',
                data: {p : id},
                type: "POST",
                dataType: "Json",
                success: function(data){
                    console.log(data);
                    $('#drpModel').empty();
                    for (let i = 0; i < data.data.length; i++){
                        $('#drpModel').append("<option value ='" + data.data[i].value + "'>" + data.data[i].text + "</option>");
                    }
                }
            });
        });
    });
</script>

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

Instructions for utilizing lodash or JavaScript to apply a filter to an object

Received this object from the Server: var data = { test1: { documents: [] }, test2: { documents: [{ vId: 'sdfas23', TypeId: '81', isDeleted: false }], answer: true }, test3: { documents: ...

The initiation of an AJAX request in Android appears to be unsuccessful

My code for retrieving JSON data from the server doesn't seem to be working. There are no logs in logcat coming from "log.v". I also feel like my try-catch statements are not effectively handling errors all the time. I am using a query for the ajax re ...

Populate the JTable with SparQL query results in JSON string format

Trying to populate a jtable with json data, I experimented with various solutions such as: String json = " ObjectMapper mapper = new ObjectMapper(); List<User> users = mapper.readValue(json,TypeFactory.defaultInstance().constructCollectionType(List ...

Using ng-options with the Add New feature is not compatible with the select statement

Hello everyone, I have some JSON values that look like this: [{"Employee":{"Emp_id":"EF00001","First_name":"Aruna","Last_name":"Jayalath"}}] Unfortunately, I am having trouble retrieving the values within the select statement when running this function i ...

What are the available events offered by Express websockets?

I am interested in learning about the different websocket events available. Currently, I have only used the ws.on('message') event, but I would like to find out how to detect when the connection is established and closed. I attempted to add the w ...

Guide to incorporating WebElement scrolling in Selenium using Java?

I need to implement a scroll function for a table on my webpage rather than scrolling the entire page, so using window.scrollBy is not an option. After attempting to find the container responsible for the scroll functionality in the DOM (with no luck), I ...

Guide on detecting and capturing a change in location history event

My main goal is to capture router change events outside of the NextJS framework, not within it. The application I have developed using NextJS includes some code that operates independently of the NextJS context. This code needs to be able to detect navigat ...

What is the most effective method for transferring resolved promise values to a subsequent "then" chain?

Currently, I am grappling with understanding promises by utilizing the Q module in node.js. However, I have encountered a minor setback. Consider this scenario: ModelA.create(/* params */) .then(function(modelA){ return ModelB.create(/* params */); } ...

Distinguishing Between URLs for Google Maps JavaScript API

Can you explain the discrepancy between two Google API URLs? One is https://maps.google.com/maps/api/js?key={api_key}, which is currently not functioning and returns an error when attempting to use it on a map to display coordinates. The other is https:/ ...

Type of Angular Service Issue: string or null

I'm encountering a persistent issue with my Angular code, specifically while calling services in my application built on Angular 13. The problem arises when trying to access the user API from the backend, leading to recurrent errors. Despite extensive ...

The error message is indicating that the function "req.assert" is not

Can you identify the issue with this code snippet (express 4.16.0, TypeError: req.assert is not a function)? userController.signupPost = function(req, res, next) { console.log(req.body); var express=require('express'); var validator = require(&a ...

Using ng-class in Angular.js with a boolean retrieved from a service: A step-by-step guide

I need to dynamically set a class based on a boolean value that is determined in a service. This example is simplified for readability, but in reality, the boolean would be set by multiple functions within the service. Here is how it would look in HTML: ...

Looking for matching index in rotated array

Currently, I am working on a design with a reference rectangle (colored in red). Within a rotated container div (#map), I am trying to create a duplicate rectangle (in yellow) that matches the size and position of the original "base" rectangle, regardless ...

Elements that allow for asynchronous data submission without requiring a traditional submit button

Hey there, I could really use some help with this puzzle I'm trying to solve. Here's the situation: <ul> <li>Number: <span id="Number">123</span></li> </ul> I want to set up a connection between t ...

How can I use Node.js Express to send a response in a file format like JavaScript or another type?

Currently, I have a piece of code that successfully reads the 'example.js' file and sends it to the client as requested. app.get('/mods/example.js', function(req, res) { fs.readFile('./mods/example.js', {encod ...

Is there a way to conceal the headers during an ajax request?

I'm currently exploring APIs using jQuery and Ajax. To set the header of Ajax, I typically use code similar to this: headers: { "My-First-Header":"first value", "My-Second-Header":"second value" }, I am working on a basic school project and ...

Tips for avoiding fields containing the symbol "$" in their name

Is it possible to query a JSON document that contains field names with special characters like "$id"? SELECT [ID] FROM OPENJSON( '[{"$id":42},{"$id":43}]', '$' ) WITH ([ID] NVARCHAR(25) '$.$id') WHERE ID = ...

JavaScript - Validation Tool for Bootstrap

Currently utilizing a plugin called Plugin Link Attempting to validate whether at least one checkbox from a group has been selected. Unfortunately, the plugin does not offer this feature. After some research, came across a discussion by the plugin author ...

The hamburger menu for mobile devices is not functioning properly on the website's mobile version, however it operates correctly when the screen is resized

Currently, I am facing an issue with the hamburger menu not responding on my mobile device. Oddly enough, it does work when I resize my browser window to mimic a mobile size. There seems to be a glitch happening, but I'm struggling to pinpoint the exa ...

make the chosen text appear on Internet Explorer

1 How to insert text into a text box using code? 2 Moving the caret to the end of the text. 3 Ensuring the caret is visible by scrolling the text box content. 4 Programmatically selecting specific text in a textbox. 5 **How to make selected text visible?** ...