Issues with loading cascading drop down list data from database using MVC, JSON, and C#

Hello everyone,

I'm fairly new to MVC/Javascript and have been experimenting with different tutorials in order to create a cascading drop down list for selecting State and City on an MVC view. In my latest attempt, I followed this example.

While the states populate from the database successfully, the cities dropdown remains blank with about 10 empty spaces, regardless of the state selected. Can anyone point out what I might be missing? Any advice or feedback is greatly appreciated!

Here is some information about the database tables:

- Regions (contains states): Id (Primary Key Int), Name (Varchar(255) state/regionname), CountryId (Int)
- Cities (Contains cities): Id (Primary Key Int), Name (Varchar(255) city/name), RegionID (int, linked to region table)

Here is the view model:

public class UserAds
{
    public int addId { get; set; }
    public int userCreatedAcctId { get; set; }
    public string userForAccEmail { get; set; }
    public string photoFileLocation { get; set; }
    public string addTitle { get; set; }
    public string addDesc { get; set; }
    public string addPersonalityTraits { get; set; }
    public string addHobbies { get; set;}
    [Required]
    [Display(Name = "State / Region")]
    public int stateId { get; set; }
    [Required]
    [Display(Name = "City")]
    public int cityId { get; set; }
}

Here is the controller:

        [HttpGet]
    public ActionResult CreateAd()
    {
        List<Region> stateList = db.Regions.ToList();
        ViewBag.StateList = new SelectList(stateList, "Id", "Name");
        return View();
    }

    public JsonResult GetCitiesList(int StateId)
    {
        db.Configuration.ProxyCreationEnabled = false;
        List<City> CityList = db.Cities.Where(x => x.RegionId == StateId).ToList();
        return Json(CityList, JsonRequestBehavior.AllowGet);
    }

The view:

<div class="container">
<div class="form-group">
    @if (ViewBag.StateList != null)
    {
        @Html.DropDownListFor(model => model.stateId, ViewBag.StateList as SelectList, "--Select State--", new { @class = "form-control" })
    }
</div>
<div class="form-group">
    @Html.DropDownListFor(model => model.cityId, new SelectList(" "), "--Select City--", new { @class = "form-control" })
</div>

Javascript Code:

<script>
$(document).ready(function () {
    $("#stateId").change(function () {
        $.get("GetCitiesList", { StateId: $("#stateId").val() }, function (data) {
            $("#cityId").empty();
            $.each(data, function (index, row) {
                $("#cityId").append("<option value=" + row.Id + "'>" + row.Name + "</option>")
            });
        });
    })
});

To debug JavaScript code in Internet Explorer, you can use this Javascript debugger.

Answer №1

The line below is missing a single quote after value=

$("#cityId").append("<option value=" + row.Id + "'>" + row.Name + "</option>")

The correct version should look like this-

$("#cityId").append("<option value='" + row.Id + "'>" + row.Name + "</option>")

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

What causes nodejs to exit prematurely without running all the code?

When running the code provided, it randomly prints "DONE" or not. Can you explain why this happens? How can I ensure that it always reaches the console.log("DONE"); line every time? const {Worker, isMainThread, parentPort} = require('node:worker_threa ...

`Issue with writing to file in Node.js`

A file is being cropped and loaded on the Angular side. I am grateful for this resource that has facilitated this process. SignUp2ControllerTest -- $scope.upload --> data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQVR4Xmy9 ...

Updating field based on dropdown value in CakePHP 3.6.11

I have the following tables: customers[id, name, surname, phone, text, balance, created] service_types[id, title, price, length, is_subscription, created] customer_service_types[id, customer_id, service_type_id, price, created] Within the add.ctp file o ...

React - Implementing dynamic component rendering on a webpage

My component, Item.js, is static. Routes.js export default () => ( <Provider store={store}> <BrowserRouter> <Switch> <Route path="/posts" component={Posts} /> <Route path="/form" component={Postfo ...

What is the best way to eliminate concealed divs from the view source of a webpage?

On my HTML page, I have some hidden DIVs that can still be viewed in the page source. I want to ensure that these DIVs are not visible to users when they inspect the page source. Is there a way to achieve this using Javascript or another solution? ...

Using PHP to create redirects within an iframe

Imagine I have embedded an iframe to showcase a different website on my own site. However, when the displayed site contains a redirect that directs to other pages within its domain, this results in the entire browser being redirected to the external site w ...

Cross-origin resource sharing (CORS) allows for the secure transfer of data across different

Currently, I am faced with a challenge in making an XmlHTTPRequest POST request from a page loaded via HTTPS to a different domain using an HTTP URL. The HTTP server in question is local and does not support HTTPS due to being within a home setup (like a s ...

I could use some assistance with accessing the /results page on the OMDb API following a movie search by

Presented here is my app.js code. My objective is to develop a movie search feature that enables me to look up a movie in a database and retrieve results for 10 movies related to the entered keyword. For instance, if I input "ALABAMA", the system should re ...

Master the art of MongoDB Aggregate with these simple steps!

Here is a sample data object: [ { "_id": "56bab”, "region": “AS”, “spentOn”: [ “56bf623a0c90b5” ] }, { "_id": "57bab", "region": "EU", "spentOn": [ "b5”, "b6”, "b8”, ] }, ...

invoking a JavaScript function with onClick

Every time I try deploying my code, an error is thrown saying: saveRows is not a function. Can anyone help me figure out what's going on? dataGrid.prototype = { display: function() { var self = this; var html = []; va ...

What are the best practices for securely storing SSL certificates and public/private keys?

I possess keys that appear like this. MIID0DCCArigAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJGUjET MBEGA1UECAwKU29tZS1TdGF0ZTEOMAwGA1UEBwwFUGFyaXMxDTALBgNVBAoMBERp bWkxDTALBgNVBAsMBE5TQlUxEDAOBgNVBAMMB0RpbWkgQ0ExGzAZBgkqhkiG9w0B CQEWDGRpbWlAZGltaS5mcjA ...

Execute an AJAX call to remove a comment

Having some trouble deleting a MySQL record using JavaScript. Here is the JavaScript function I am trying to use: function deletePost(id){ if(confirm('Are you sure?')){ $('#comment_'+id).hide(); http.open("get","/i ...

Tips for determining the time and space complexity of this JavaScript code

Here are two codes utilized by my platform to establish relationships between nodes. code1 : const getNodeRelationship = (node1, node2) => { // if node1 and node2 are the same node if (node1 === node2) return null; // check direct parent ...

Use Vue's DOM manipulation to properly surround iframes with divs

I'm facing a scenario where my Vue component displays HTML content retrieved from the database in the following format: <div id="post-body-text" class="post__main-text" v-html="postText" ...

Issue with callback function not triggering after comment deletion in REACT

Although I am successfully able to delete the comment, I am facing an issue where the callback function is not being invoked. My suspicion is that it might be related to how I pass multiple arguments to the function, but I cannot confirm this. Below is th ...

Modifying all occurrences of a specified string in an object (or array) - JavaScript

Is there a more efficient way to search through and replace all instances of a given string in a JavaScript object with unknown depth and properties? Check out this method, but is it the most optimal solution? var obj = { 'a' : 'The foo ...

Stop the automatic inclusion of specific values when using PHP's json_encode() function

When I utilize PHP's json_encode function to convert an array into a JSON string, is there any way to stop certain values from being enclosed in quotes? The reason behind my inquiry is that I require JavaScript to interpret specific values within the ...

Generate an array consisting of characters within a designated range

I recently came across some Ruby code that caught my attention: puts ('A'..'Z').to_a.join(',') The output was: A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z I'm curious if there is a similar way to achieve this ...

What is the best way to utilize the oninput function in Jade?

input(type='range', id= 'inputSlider', min='0', max='255', value='50', step='1', oninput=showValue(this.value)) span#outputText 50 script. var socket = io.connect(); socket.on(& ...

Gradually conceal the final column of an HTML table with the combination of CSS and JavaScript

My challenge involves modifying a table on Sharepoint with responsive design in mind. The goal is to hide the last visible column in the table based on the screen's width. For instance, if a user creates a 10-column table and the screen size is 1200p ...