How to Effortlessly Populate Cascading Dropdowns in ASP.Net MVC 5 using a Reusable

I am currently working on an ASP.Net MVC 5 application that has multiple edit pages. Each edit page consists of various input elements such as textboxes, checkboxes, and dropdowns. I want to implement a functionality where the values of one dropdown are changed based on the selected values of another dropdown.

In order to achieve this, I aim to create a reusable and generic JavaScript function that will make an AJAX call with specific parameters and update the content of a designated HTML tag with the result (either HTML or JSON).

Considering the high probability of someone else already having similar requirements, I don't want to reinvent the wheel. Is there any existing solution or jQuery plugin available for accomplishing this task that I might have missed while searching?

To be more specific, here is my envisaged approach:

Input parameters:

  • Ajax URL to invoke the necessary controller action
  • Arguments to send to the controller (by default, it should include the selected value of the first dropdown, but there may be cases where additional values or even the entire form needs to be sent)
  • Target: A jQuery selector indicating the HTML element where the resulting HTML should be placed
  • (Possibly other parameters: configuring the request method as POST or GET; specifying whether the target should be added or replaced; defining OnSuccess/OnError handlers; etc.)

I initially thought that jQuery Unobtrusive would provide something like this, but unfortunately, it doesn't meet my requirements.

(I am not using any JavaScript frameworks like Knockout or AngularJS, and I don't want to introduce them solely for this specific functionality.)

Answer №1

I would suggest creating your own solution for this task. One approach could be to develop a function that takes in parameters such as the post URL, newly selected value, and step number. This function can then return a JSON list of values which can be used to populate the next dropdown menu.

Here is an example implementation:

<select name="Countries" multiple="multiple">
    <option value="USA">United States</option>
    <option value="UK">United Kingdom</option>
    <option value="JP">Japan</option>
</select>
<select name="Cities">
</select>

.... // later inside the script

var fetchStepOptions = function(postUrl, newSelectValue, currentStep){
    var postData = {
        NewSelectValue: newSelectValue,
        CurrentStep: currentStep
    }

    $.ajax(
    {
        type: "POST",
        data: JSON.stringify(postData),
        url: "postUrl",
        contentType: 'application/json; charset=utf-8'
    }).done(function(values) {
        return values; // parsing may be required
    })
    .fail(function() {
        return ["failed"];
    });
}

var updateSelectedValues = function($select, selectedVal, step){
    $select.empty();
    var newSelectVals = fetchStepOptions("fetchOptionValuesUrl", selectedVal, step);
    $.each(newSelectVals, function(val){
        $select.append($("<option></option>")
            .attr("value", val).text(val));
    });
}

$("[name='Countries']").click(function(e) {
    var $selectToModify = $("[name='Cities']");

    updateSelectedValues($selectToModify, $selectToModify.val(), 1);
}

Please note that I wrote this code directly in this window without executing it, so there may be potential errors. If I have time, I might run the code later and make any necessary corrections.

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

Required Field Validation - Ensuring a Field is Mandatory Based on Property Length Exceeding 0

When dealing with a form that includes lists of countries and provinces, there are specific rules to follow: The country field/select must be filled out (required). If a user selects a country that has provinces, an API call will fetch the list of provinc ...

Incorporating an external HTML page's <title> tag into a different HTML page using jQuery

I am faced with a challenge involving two files: index.html and index2.html. Both of these files reside in the same directory on a local machine, without access to PHP or other server-side languages. My goal is to extract the <title>Page Title</ ...

PhantomJS Karma encountering SyntaxError when trying to export variables

I've encountered an issue while running Karma and PhantomJS. When I attempt to run, the console displays the following message: 22 03 2016 14:58:47.865:WARN [karma]: No captured browser, open http://localhost:9876/ 22 03 2016 14:58:47.875:INFO [karm ...

What could be causing the fourth tab to not show any data while the first three tabs are functioning as expected?

I've encountered an issue with my HTML tabs. While I can easily switch between the first three tabs and view their content, tab 4 doesn't seem to display its associated data. It's puzzling why tab 4 is not working when the others are functio ...

What are the differences between a Chrome app and extension? Is there any other way to access the tabs currently open in your

I need to develop an app that can access the tabs a user has open, but I'm struggling to find a way to do so without having my app run in Chrome itself. Creating an extension restricts the UI significantly, which is problematic since my app requires a ...

Retrieve file from Ajax request within MVC C# Application

Having an issue while attempting to download an SSRS report from a MVC C# application. I am using an HttpResponseBase object and sending it back to the user as a response, but all that is displayed are symbols. Any assistance on what might be missing upon ...

Using Vue.js to dynamically calculate elapsed time

I am attempting to display the changing elapsed time from a specified start time <template> <div class="dashboard-editor-container"> <div class="wrapper__body"> <el-row :gutter="30"> <el-col v-fo ...

Updating Text within a Label with jQuery

Seeking assistance with a jQuery issue that I am struggling to resolve due to my limited experience. Despite attempting to search for solutions online, I have been unable to find an alternative function or determine if I am implementing the current one inc ...

Shopify's Ajax Cart experiences persistent loading issues when attempting to insert an <img> element within the code

I'm currently experiencing some difficulties when trying to insert a small image beneath the Check Out button on Shopify. I have attempted various locations without success, and I am using the Brooklyn theme. My approach involves using liquid tags an ...

Vue and Vuex retrieve state data from the server in a single request

When loading the History view, data is fetched from the backend server using a Vuex action called in the created() lifecycle hook. This data is then passed to the history table through a computed function named history(), which accesses the history module ...

What is the most effective way in MongoDB to insert data only if it does not already exist in the database?

Is there an optimal way to insert data into MongoDB only if it doesn't already exist in the table? The unique field for searching is hash, which is also indexed. router.post('/', async (req, res) => { try{ var id = null const ...

Utilizing styled-components or personalized components alongside cypress

Cypress selector made simple: just use cy.get('.myComp') and it will select <input className="myComp" />. But when it comes to styled-components... Perhaps we have to resort to using custom attributes like cy-data or cy-testid. Sadly, it s ...

Storing input values in the state using Typescript by default

Upon launching, my activeField state is initially empty. However, when a user focuses on the field, it gets added to the state. I am encountering a warning in Typescript because when I attempt to update the selectionEnd of that field, it tells me: Property ...

Creative jQuery hover effects tailored to the size of the viewport

Currently expanding my knowledge of jQuery and encountering an issue with some code. I am trying to incorporate an animation effect (fadeIn/fadeOut) when the user hovers over a specific element. However, if the viewport is resized to below 480px for mobil ...

What is the process of setting up various initialization parameters for a DataTable?

Here is a snippet of JavaScript code I have been using to initialize a DataTable: $(document).ready(function() { $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'copyHtml5', &a ...

How can I personalize the color of a Material UI button?

Having trouble changing button colors in Material UI (v1). Is there a way to adjust the theme to mimic Bootstrap, allowing me to simply use "btn-danger" for red, "btn-success" for green...? I attempted using a custom className, but it's not function ...

What is the correct way to navigate data through my Node.js API?

I am struggling with getting the JSON response to display at the /api/orders_count endpoint. Here is a breakdown of my setup: In my project, I have various files: Routes file - where the orders_count route is defined: routes/index.js const express = req ...

Update a separate React component in response to the interaction with a different React component

Currently, I am working with a react component named Interest Category that showcases an initial set of Interest categories. Another react component called CreateInterestCategoryDialog, which functions as a modal, is responsible for creating a new entity I ...

Bringing the value from the codebehind to the jquery function on the client side

Here is the code snippet from my asp.net web application's code behind where I have integrated another web service: [WebMethod] public static string GetData(string name) { WEBSERVICE.Service1 Client = new Service1(); string Nam ...

Guide to extracting the values associated with a specific key across all elements within an array of objects

My goal is to retrieve the values from the products collection by accessing cart.item for each index in order to obtain the current price of the product. const CartSchema = mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ...