execute an action in the controller with the help of JavaScript and refresh the view

My scenario involves having multiple selects such as brands and products. I aim to dynamically update the products options based on the brand selected by the user. The select element looks like this:

<select asp-for="Product.BrandId" class="form-control" asp-items="ViewBag.BrandId" id="transactionBrand" onchange="brandSelect()</select>

After obtaining the brand id that the user selected with JavaScript, I am unsure about the next steps. My plan is to invoke an action within a controller to retrieve the list of products, update the ViewBag for product selection, and then return to the current view. How can I accomplish this?

Answer №1

If you want to pass a selected brandId to an action using ajax and have the action return a list to set select options in javascript, you can follow this example: Model:

public class Product
    {
        public int BrandId { get; set; }
        public int ProductId { get; set; }

    }

Controller (Using fake data for testing):

[HttpGet]
        public IActionResult TestProduct() {
            ViewBag.BrandId = new List<SelectListItem> { new SelectListItem { Text = "brand1", Value = "1" }, new SelectListItem { Text = "brand2", Value = "2" }, new SelectListItem { Text = "brand3", Value = "3" } };
            ViewBag.ProductId = new List<SelectListItem> { new SelectListItem { Text = "select product", Value = "" } };
            return View();
        }
        [HttpPost]
        public List<SelectListItem> TestProduct(int BrandId)
        {
            List<SelectListItem> l = new List<SelectListItem> { new SelectListItem { Text = "product1", Value = "1" }, new SelectListItem { Text = "product2", Value = "2" }, new SelectListItem { Text = "product3", Value = "3" } };
            return l;
        }

View:

@model xxx.xxx.Product
<select asp-for="BrandId" asp-items="ViewBag.BrandId" id="transactionBrand" onchange="brandSelect()"></select>
<select asp-for="ProductId" asp-items="ViewBag.ProductId" id="transactionProduct"></select>
@section scripts{
    <script>
        function brandSelect() {
            $.ajax({
                type: "POST",
                data: { BrandId: $("#transactionBrand").val() },
                url: 'TestProduct',
            }).done(function (data) {
                var items = '';
                $("#transactionProduct").empty();
                $.each(data, function (index, Product) {
                    items += "<option value='" + Product.value + "'>" + Product.text + "</option>";
                });
                $('#transactionProduct').html(items);
                })
            
        }
    </script>
}

Result: https://i.sstatic.net/5wbH9.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

EJS unable to display template content

I am having an issue with rendering a template that contains the following code block: <% if(type === 'Not Within Specifications'){ %> <% if(Length !== undefined) { %><h5>Length: <%= Length %> </h5> <% ...

Renewing Firebase User Token in Angular Using HTTP Interceptor

I've encountered a puzzling issue while implementing error handling in my Angular HTTP Interceptor code. It appears that the code within my chain of ".then()" statements is being triggered out of order somehow. Here's a snippet of my code... im ...

Aggregate array based on specified criteria in ReactJS

Let's consider the following array data: array = [ { id: 1, count: 0.5 cost: 100 user: {id: 1, name: "John 1"}, type: {id: 1, name: "T1"}, period: {id: 1, name: "2021"} ...

The Angular Date Pipe is currently unable to display solely the Month and Year; it instead presents the complete date, including day, month,

I'm currently using the Bootstrap input date feature to save a new Date from a dialog box. However, I only want to display the month and year when showing the date. Even though I added a pipe to show just the month and year, it still displays the mont ...

Issue encountered while attempting to load Google Maps markers using loadJSON

I am currently working on a project involving Complex Markers in Google Maps, using an example from the documentation. However, I encountered an error message that reads: Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating &ap ...

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

NodeJS/ExpressJS API exposure

Currently, I am developing a website using Express and implementing route handling with the help of express router. The routes I have set up so far include registration, login, upload, and more. One particular route, upload, requires files to be uploaded ...

Adjust the text appearance of the graph in ApexCharts

Is there a way to adjust the font size of the donut chart generated by using apexchart? You can view the image here. <template> <section> <v-card raised> <v-card-title class="blue--text">Requests Overview</v-card-ti ...

What is the process for updating IDs and names for duplicated elements?

I have created a select box and used the clone function to generate dynamic select boxes. However, the cloned select boxes have the same ids and names as the original. How can I change the ids and names of the cloned elements in my code sample below: < ...

Dynamic web interactions with jQuery Ajax and PHP session handling

My web page features 3 tabs in the main content area. When a user clicks on a tab, I utilize jquery and ajax to retrieve data from the server without having to reload the entire page, subsequently changing some div elements below the tabs. The data is fet ...

Charting data with missing values in Google Charts

I have generated a line chart using php and json to load the data. The issue I am facing is that the chart displays NULL values as 0, which does not look good. My assumption is that I may be formatting the json incorrectly, and what I really need is {"v" ...

Problem with opening the keyboard feature in an Ionic app

Hello everyone, I'm relatively new to Ionic development and I've been trying to integrate a keyboard plugin into my application that opens from the footer and focuses on input fields for entering values. Here is the link to the plugin I used: ht ...

Guide on displaying a tooltip for an object in an Angular component using Bootstrap syntax

i have a data object structured like this var obj = {"test price type ty dynamic ": 10, test: 7, pricetype1u: 0, Price type 3: 0, Price type 2: 0} in my Angular component HTML, with Bootstrap styles applied, I've written the following code ...

Using socket.io in a Django template without the need for the node.js service or socket.io.js file

I am working on a Django app that requires real-time push to clients. I have decided to use node.js and socket.io as it is considered the easiest platform for achieving this functionality. To implement this, I have included the socket.io framework code in ...

The concept of position() is often mistaken for a function

I am currently developing a slider and have included the code below: $(document).ready(function() { // MAKE SLIDER WIDTH EQUAL TO ALL SLIDES WIDTH var totalWidth = 0; $('.slide').each(function() { totalWidth = totalWi ...

Tips for emphasizing specific text within HTML tags without highlighting the tags in Vue

I am using a tag with v-html to render HTML text and display it, like so: <div v-html="htmlText"></div> I have written code to highlight text and it works on regular text: Vue.filter('highlight', function (word, query) { ...

Issue with Bootstrap 5 Modal Overlay

I created a function that automatically generates a modal to save time and keep the code organized. This way, the HTML and JS related to the content of the modal are all in one PHP file, rather than mixed in with the file calling the modal: function new_mo ...

Transfer information using the Ajax jQuery technique

I would greatly appreciate your assistance. Can you please help me with one more thing? I have the code below and I am having trouble figuring out where I am making a mistake: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.j ...

"Users have reported that the Express body-parser feature sometimes results in req.body returning

I have developed a basic Express server that utilizes the body-parser module to access POST parameters. Here is how my application is structured: /index.js: 'use strict'; const express = require('express'); const app = express(); con ...

What is the syntax for implementing an if-else statement?

Just starting with algolia and looking for a hit template. Please take a look at the script below for the text/html template needed: <script type="text/html" id="hit-template"> <div class="hit"> <div class="hit-image"> <i ...