Issue with Sequential Drop Down List Functionality in ASP.Net MVC View Page

I am currently in the process of migrating code from one project to another. Although the code works fine in the original project, it is not functioning properly in the new one. I’m uncertain if something was overlooked on my end.

Within this code, there are 3 dropdown lists that are interdependent - Country, State, and City, where Country is independent.

UPDATE: Added Model

    public IEnumerable<SelectListItem> Countries { get; set; }
    public IEnumerable<SelectListItem> States { get; set; }
    public IEnumerable<SelectListItem> Cities { get; set; }

UPDATED: Here’s the dropdown code:

<div class="form-group">
   @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label" })
   @Html.DropDownListFor(model => Model.Country, Model.Countries, "---Select Country---", new { @class = "", @id = "ddlCountry" })
   @Html.ValidationMessageFor(model => model.Country, "", new { @class = "text-danger" })
 </div>

 <div class="form-group">
   @Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label" })
   @Html.DropDownListFor(model => model.State, new List<SelectListItem>(), "---Select State---", new { @class = "", @id = "ddlState" })
   @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
 </div>

 <div class="form-group">
   @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label" })
   @Html.DropDownListFor(model => model.City, new List<SelectListItem>(), "---Select City---", new { @class = "", @id = "ddlCity" })
   @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
 </div>

UPDATED: My Javascript:

<script type="text/javascript">
$(function () {
    $('#ddlCountry').change(function () {
        //debugger;
        $.ajax({
            type: "post",
            url: "/States/Add",
            data: { countryId: $('#ddlCountry').val() },
            datatype: "json",
            traditional: true,
            success: function (data) {
                $.each(data, function (index, value) {
                    $('#ddlState').append('<option value="' + value.StateId + '">' + value.StateName + '</option>');
                });
            }
        });
    });

    $('#ddlState').change(function () {
        $.ajax({
            type: "post",
            url: "/Cities/Add",
            data: { stateId: $('#ddlState').val() },
            datatype: "json",
            traditional: true,
            success: function (data) {
                $.each(data, function (index, value) {
                    $('#ddlCity').append('<option value="' + value.CityId + '">' + value.CityName + '</option>');
                });
            }
        });
    });
});

UPDATED: Controller included:

public ActionResult Create()
    {
        try
        {
            GeneralEntities generalEntities = new GeneralEntities();
            List<SelectListItem> countryNames = new List<SelectListItem>();
            VendorViewModel casModel = new VendorViewModel();

            List<Countries> countries = generalEntities.Countries.ToList();
            countries.ForEach(x =>
            {
                countryNames.Add(new SelectListItem { Text = x.CountryName, Value = x.CountryId.ToString() });
            });
            casModel.Countries = countryNames;

            return View(casModel);
        }
        catch (Exception)
        {

            return View();
        }
    }
    //Get States --- Resides in the StatesController
    public JsonResult Add(string countryId)
    {
        int Id;
        Id = Convert.ToInt32(countryId);

        var states = from a in db.States where a.CountryId == Id select a;
        return Json(states, JsonRequestBehavior.AllowGet);

    }

The list doesn’t populate, and upon debugging in the console window, a 500 server error is shown. Could it be a permission issue or a missing piece of code?

Thank you for your assistance.

UPDATE: Stack Trace..

There is already an open DataReader associated with this Command which must be closed first.
...

UPDATE: I attempted to add ‘MultipleActiveResultSets=True’ to my connection string as recommended elsewhere, but it caused issues with my security token.

UPDATE: Although no errors appear now, the States List still isn’t populating after selecting a Country. The perplexity lies in why the original solution worked while this one does not...

UPDATE: This has been moved to a different question due to a suspected script conflict! Additional details can be found here: stackoverflow.com/questions/60386156

Answer №1

Have you attempted adding the full server URL to the ajax call and including the [HttpPost] attribute on the action method?

[HttpPost]
       public JsonResult Add(string countryId)
        {
            int Id;
            Id = Convert.ToInt32(countryId);

            var states = from a in db.States where a.CountryId == Id select a;
            return Json(states, JsonRequestBehavior.AllowGet);

        }

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

How to Retrieve Upload Progress via HTTP Request in PHP

Is there a way to monitor the progress of file uploads by accessing the HTTP request in PHP? If so, how can this be achieved when uploading files into a MySQL database? require('../connect_db.php'); //Collect all necessary data $name = $dbc-> ...

What is the process for applying a border to the chosen image within the ImageList of the MaterialUI component?

Currently, I have set up the images in a grid format using the and components from MaterialUI. However, I am looking to implement an additional feature where when a user clicks on a specific image from the grid, a border is displayed around that select ...

Analyze two sets of JSON data and compile a new JSON containing only the shared values

I am trying to generate two JSON arrays based on a shared property value from comparing two sets of JSON data. this.linkedParticipants =[ { "id": 3, "name": "Participant 2", "email": "<a href="/ ...

Is it possible to ensure only one value is set as true in useReducer without manually setting the rest to false

I am seeking a more efficient method to ensure that only one value is set to true while setting the rest to false I came across this Python question and answer recommending an enum (I am not very familiar with that concept) Currently, I have the followin ...

Issue with redirect using Node.js promise

I’ve created a settings page where users can add and remove filters. To handle the deletion process, I’ve implemented this jQuery function: $('#delete-filter').click(function (e) { var filtername = $('#filter-list').val(); ...

Is there a way I can create a conditional statement to determine the values of my selection?

I need to customize the order status values for 'confirmed', 'on the way' and 'delivered'. How can I map these statuses to specific numerical values based on the options available in a select menu? Confirmed - 10 On the way - ...

Struggling to forward JSON data via AJAX to Django without relying on jQuery

My goal is to utilize AJAX in conjunction with Django, but I want to achieve this without relying on jQuery. So far, I have made progress in sending URL encoded data from AJAX to Django successfully. However, I am currently facing an issue where I am unabl ...

What is the best way to extract the text from a label using Selenium?

It seems like I can select the element using CSS Selector, Xpath, or TagName, but I'm having trouble retrieving the associated text. Here is a snippet of the HTML code: <label for="AnswerText">This is the question text? </label> In my c ...

Utilizing Jquery to pass two classes along

I am looking for assistance on how to pass multiple classes within if-else statements and jQuery. My goal is to have both divs and divs2 change when the next button is clicked. Can someone please provide guidance on achieving this? --code not mine-- ...

Transmit information from the frontend to the backend using JavaScript and the Express framework

After creating a custom variable in my frontend to store data, I needed to access the same data in my Express backend. The JavaScript variable and the POST request code snippet are as follows: const dataPush = { urlSave: urlSave, ...

Add HTML content to an element within a directive and create a custom function to manipulate it locally

In my AngularJS application, I am faced with a variety of complex inputs scattered throughout. Some inputs utilize directives for autocompletion functionality, like those powered by Google Places or Twitter Bootstrap. I am currently exploring the concept ...

Having trouble translating SQL query into dataview Rowfilter

I am having trouble converting my SQL query with a case when condition on rowfilter in C#. Here is the original SQL query: select * from myview where myview.CHARGE_CODE = (CASE WHEN 'ALL' = 'ALL' THEN ...

Ninject does not have a registered IUserTokenProvider for ASP.NET MVC

Encountering the error message No IUserTokenProvider is registered upon calling _userManager.GenerateEmailConfirmationTokenAsync(user.Id); to generate a token for an account registration email. Despite researching various related posts, none have successfu ...

Discover the underlying element that is being blurred when clicked

Is there a method to determine which element triggered the blur event when clicked outside? I want to update a ui-select value to match what the user typed in if they click outside of the dropdown. However, if they click on a dropdown item, I want to disc ...

Encountering an issue with Invariant Violation when attempting to retrieve a frame that is outside of the specified

I have created a VenueList component for my React Native app. I want to utilize the FlatList component to display a list of venues, but I keep encountering an error message that says "Invariant Violation tried to get frame out of range index" (refer to the ...

What is the best way to include multiple entries in a select2 form using ajaxform?

select2/3.5.2/ I had to repost this because my initial post was not formatting correctly. The tools in use are: A select2 form field that allows searching through multiple records A bootstrap popup modal containing a form for entering a new record if i ...

Tips for accessing <Field> values in redux-form version 7.0.0

class CustomForm extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { const { Add, noteList } = this.props; Add('this is title value' , 'this is ...

switching the icon for custom sorting in AngularJS

I managed to implement a custom grid style and sorting icon in AngularJS successfully, except for the toggling of the sorting icon. Here is my HTML code for headers: <div ng-app="myApp"> <div ng-controller="TableCtrl"> <table ...

Close the overlay by clicking outside of it

I'm working on creating a unique pop-up window that appears when a customer adds a product to their cart. The design features red and green background divs with a darker overlay (#overlay-daddy) and a white child div (#overlay). My issue arises from ...

Error code 1 encountered an internal error while trying to execute a task

Currently, I have this job set up to clear out unnecessary records. The code provided has been simplified for debugging purposes. However, almost 80% of the time when running it, it fails to find anything due to Error code 1 "internal error": Parse.Cloud. ...