Use the json method and JavaScript to bind the data

I have been attempting to fetch data for a dropdownlist using JSON. While the program is functioning correctly, the dropdownlist is displaying a blank list. Upon inspection, I can see that the data is present but not being displayed.

Controller:

    public IActionResult GetClient()
    {
        var clientList = (from client in _context.Clients
                          select new SelectListItem()
                          {
                              Text = client.Nom,
                              Value = client.Id.ToString(),
                          }).ToList();

        clientList.Insert(0, new SelectListItem()
        {
            Text = "----Select----",
            Value = string.Empty
        });

        return Json(clientList);
    }

Script:

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "/Clients/GetClient",
            success: function (data) {
                $.each(data, function () {
                    $("#ClientId").append($("<option></option>").val(this['Value']).html(this['Text']));

                });

            }
        });
    });
</script>

HTML Code:

                </div>
                <div class="alert-danger" asp-validation-summary="ModelOnly"></div>
                <label asp-for="ClientId"></label>
                <select asp-for="ClientId"
                        class="form-control"
                        asp-items="@(new SelectList(Enumerable.Empty<SelectListItem>(),"Value", "Text"))">
                </select>
            </div>

            <div>

Thank you for your assistance

Answer №1

The dropdownlist is supposed to display a white list of data, but upon inspection, the data is there yet not being displayed as intended.

The issue is quite evident. Upon inspecting the HTML code, you will notice that the value and text are in lowercase, whereas in your code you have used them in uppercase like so:

val(this['Value']).html(this['Text']))
. It's worth noting that JSON object keys are typically in lowercase by default.

https://i.sstatic.net/U2c0F.png

Note: Simply replace the snippet below to completely resolve the problem.

Solution:

  $("#ClientId").append($("<option></option>").val(this['value']).html(this['text']));

Output:

https://i.sstatic.net/u6Atm.gif

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 recently started a project using create-react-app on my Windows computer. However, I encountered an error when I attempted to run npm start in the command line. Can anyone assist me in resolving this issue

Encountered an npm start error Error: code ELIFECYCLE npm ERR! errno 1 npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] start script. npm ERR! No problem with npm. Look for additional logging. npm ERR! Check log here: npm ERR! ...

The function util.promisify in NodeJs is not recognized

As I attempt to turn a mysql function into a promise, an error appears in the console saying util.Promisify is not a function. Below is the code I am using: var util=require('util'); var mysql= require('mysql'); var conecti ...

Locate a specific class inside a div and switch the CSS style to hide one element and reveal another

I have two divs, each containing a span. By default, the display of each span class is set to none. My goal is to toggle the display property of the span within the clicked div. If the span is already visible, I want to hide it; if it's hidden, I want ...

Learn How to Use JQuery/Ajax to Post Files and Models to an Asp.net Core Controller

This question is distinctive from the one found at this link as it provides a detailed explanation suitable for beginners. In my scenario, I have a view that inherits from a model. The fields are encapsulated within a form, and my objective is to utilize ...

Receiving no feedback from a public API while coding in React.js

I am currently delving into React.js and have been experimenting with a basic form. The issue I am facing is related to sending form data using ajax and not receiving a response. Upon running the code, the console displays an error message stating readysta ...

Tips on sending a list via @Input using Angular5

I was seeking guidance on how to pass a list through an input. In my parent component, I have the following: list: Hero[] = [{Id: 2, Name: "Sll"}, {Id: 3, Name: "Sldsadasd"}] and in the HTML: <app-add-hero list="{{list}}" hero={{hero}}></app-ad ...

What is the best way to incorporate a popover into a fullcalendar event displayed on a resource timeline in Vue while utilizing BootstrapVue?

I need help adding a popover to an event in a resource timeline using fullcalendar/vue ^5.3.1 in Vue ^2.6.11 with ^2.1.0 of bootstrap-vue. Although I found some guidance on Stack Overflow, the solution involving propsData and .$mount() doesn't feel l ...

Displaying a static image on an HTML5 canvas without any movement

As a novice in canvas game development, I must apologize for my lack of knowledge. I have an image with dimensions 2048px width and 1536px height that needs to be placed within a canvas (the width and height vary on different devices). While I am able to ...

Transcode Byte Array into Base64 String Using AngularJS

I am receiving a byte array in the service response, and I need to display that image in an image field on my HTML page. Can anyone provide guidance on how to implement this? I have searched for solutions on Stack Overflow but have not found a valid soluti ...

The initial output of the object yields an undefined value

Issue Description (View Code on Fiddle): The issue with this code is that the first printed result returns 'undefined'. Why does this happen and how can it be fixed? Code Snippet: var animals = { dogs: 0, cats: 0, birds: 0, fis ...

Tips for displaying a modal to a user only once

I've developed a Flask application that enables multiple users to register and log in. To achieve this, I have incorporated sessions into my code. When new users land on the initial page, they are greeted with a modal introducing them to the platform. ...

JavaScript function to toggle the visibility of navigation with a click of a button

I'm attempting to create a functionality in my code where the Open navigation button hides when the side navigation opens upon clicking. The desired behavior is for the openNav button to be hidden when it's clicked and then shown again when close ...

What is the best way to efficiently input identical data into multiple controllers ($scope) using just one call in AngularJS?

I have a situation where I am using a factory to make a call in two controllers on the same page. However, I want to avoid making an AJAX call twice. I tried using $q.defer(), but it doesn't seem to be working! Here is the code snippet: (function ...

Having trouble dynamically displaying the '<' symbol using JavaScript?

Whenever I attempt to show a string with the character '<' in it, the part of the string that comes after the symbol is not displayed. Strangely enough, when I output it to the console, it appears correctly. Take a look at this excerpt showcas ...

Adjusting Image Width with jQuery on Hover

I am trying to create a hover effect for two images placed side by side. When the user hovers over one of the images, it should expand. HTML: <a href="#"><div id="skinny"></div></a> <a href="#"><div id="room9"></div ...

Is there a way for me to modify the content on my webpage by utilizing the chosen value from an HtmlHelper DropDownList?

Currently, I am using ASP.NET MVC and need help with updating the content on my webpage based on the selected value from an HtmlHelper.DropDownList. Specifically, I have an Admin page where I intend to showcase a list of hired employees for a particular se ...

The like count displayed in Django's AJAX feature is identical for every post

Having an issue with the ajax setup in my django twitter clone app. Every post's like count remains the same after clicking the like button, but it gets updated after a page refresh. I'm close to fixing it, but currently stuck. View: def add_li ...

Utilize the reference model class within the controller to consolidate multiple data into a single view

My goal is to consolidate data from multiple SQL Server stored procedures into one view so I can conduct comparisons and generate graphs/grids. Each section works individually, but now I need to integrate them. I restructured my controller by organizing t ...

Mastering the art of reading rows in ASP.NET using Java Script

Within the code snippet below, you'll find an image located in the second column. Clicking on this second column should allow me to access the data stored in the first column. Let's say we have a table with 10 rows. If the user clicks on the ico ...

Utilizing pop-up info boxes

After thoroughly reviewing the documentation on Imagemapster's website and browsing several posts, I am still struggling to get the tooltips working correctly. I attempted to share my HTML and JS code on jsfiddle.com without success, so I have provide ...