Send a list of integers created in a JavaScript function from a Razor view to a controller

Is it possible to transfer data from JS created select tags to the controller? Here is the function responsible for generating the select tags:

function changeFunc() {
    var elements = document.getElementsByClassName('selector2');
    while (elements.length > 0) {
        elements[0].parentNode.removeChild(elements[0]);
    }
    var selector = document.getElementById('selector');
    var selectedValue = selector.value;
    console.log(selectedValue);
    @foreach (var item in Model.Rooms)
    {
            <text>
            if (@item.RoomID == selectedValue)
            {
                var selectedValue2 = @item.Capacity;
            }
            </text>
    }
    var inputContainer = document.getElementById('for-input');
    for (var i = 0; i < document.getElementById('selector').value; i++)
    {
        var selector2 = inputContainer.appendChild(document.createElement("select"));
        selector2.className = "selector2";
        var option1 = document.createElement("option");
        option1.value = "0";
        option1.text = "Choose a client";
        option1.defaultSelected = true;
        selector2.appendChild(option1);
        selector2.tagName = "ClientsIDs";
        @foreach (var item in Model.Clients)
        {
            <text>
                var optionz = document.createElement("option");
                optionz.value = @item.ID;
                optionz.text = he.decode("@item.Name");
                selector2.appendChild(optionz);
            </text>
        }
    }
}

I aim to extract the value from the "selector2" element, which has multiple instances due to being inside a loop. My objective is to compile these values into a list. I experimented with setting the "name" attribute to the property of type List, but encountered an obstacle - the loop resides in JS whereas the Model belongs to C#, making accessing the index "i" variable challenging. This was my attempt:

selector2.name("name", @Model.Reservations2.ClientsIDs[i]);

The property in question is as follows:

public List<int> ClientsIDs { get; set; }

Answer №1

To properly define the name attribute, follow this format:

selector2.setAttribute("name", "ClientsIDs[" + i +"]");

This is how it will look in HTML:

https://i.sstatic.net/8ltuC.png

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

Retrieving nested JSON object data with Angular's HTTP GET method

Currently, I am attempting to extract a URL from a JSON object that is nested, but I am encountering difficulties accessing the data. I am unsure of the method to retrieve data from a JSON object that is deeply nested. app.controller('mainCtrl', ...

Securely authenticate with Node.js using screen scraping techniques

Attempting to scrape a website with authentication in node.js, but encountering an issue when trying to submit the form: "Your browser "for others" does not support our site." The username is being set, but the password field appears to be empty. Curren ...

What is the process for exporting a class and declaring middleware in TypeScript?

After creating the user class where only the get method is defined, I encountered an issue when using it in middleware. There were no errors during the call to the class, but upon running the code, a "server not found" message appeared. Surprisingly, delet ...

conducting a validation using ajax when submitting

Currently, I am exploring the implementation of AJAX validation within a submit() handler for a web form. The AJAX functionality is executed using $.ajax() from jQuery. While setting async: false yields successful results, it triggers a deprecation notice, ...

Issue: function is not a valid type (during mount)

Currently, I'm trying to add a feature that automatically closes all menus and modals when a user clicks outside of the specified area. Although I am successfully calling this.closeMenu(), an error is occurring stating that this.closeMenu is not reco ...

Quickly view products in Opencart will automatically close after adding them to the cart and redirecting the

I've integrated the product quickview feature into my OpenCart theme, which opens a product in a popup. However, when I add a product to the cart from the popup, it doesn't update on the main page until I refresh. I'm looking for a way to re ...

Angular JS is throwing an error because angular.model is not recognized as a function

I am experimenting with some angular JS examples, but I have encountered an error that is causing me some trouble. Can someone please assist me in resolving this issue? <html> <head> <script src="http://ajax.googleapis.com/ajax/li ...

Having trouble setting the focus on a text box following a custom popup

Presenting a stylish message box and attempting to focus on a textbox afterward, however, it's not functioning as expected. Below is the HTML code: <a class="fancyTrigger" href="#TheFancybox"></a> <hr> <div id="TheFancybox">& ...

Having trouble importing a component conditionally within a nested component

I am attempting to dynamically import and render one of two components based on the value returned by a prop (lang). If props.lang is set to spanish, then it should import and render a component named <Spain />; otherwise, <UnitedStates />: /* ...

In order to enable automatic playback of background images

Having created a slider with hover functionality on icons to change background images, I now seek to add an autoplay feature to the slider. The slider was implemented in a WordPress project using Elementor and involved custom Slider creation through JavaSc ...

Toggling in JS does not alter the DIV element

I attempted to utilize Bootstrap toggle to modify the div HTML content similar to the example shown at with a slight modification, but unfortunately, it did not function as expected due to a discrepancy in my current JavaScript code. I am unsure of what I ...

When an initial submit button activates a secondary form, the ensuing submit button on the second form initiates a POST request to the action specified in the original form

In my experience with MVC forms, I have encountered challenges when trying to submit a form and display another form. Initially, I attempted to nest forms, but soon realized that form tags cannot be nested in Asp.net MVC. Instead, I placed the forms in se ...

Error: an empty value cannot be treated as an object in this context when evaluating the "businesses" property

An error is occurring stating: "TypeError: null is not an object (evaluating 'son['businesses']')". The issue arose when I added ['businesses'][1]['name'] to 'son' variable. Initially, there was no error wi ...

Combining ng-filter and ng-repeat to iterate over key-value pairs in objects

Currently, I am utilizing the built-in Angular 1 filters in an attempt to filter out a property of an object. While Angular Filters typically only accept Arrays and not Objects, the structure of the web application prevents me from refactoring to pass an a ...

Tips for adjusting the button color in Material UI by utilizing the ":active" pseudo-class

In the project I am currently working on, I am incorporating Material UI. One of the tasks I need to complete is changing the active state of a button. I have implemented both hover and active states from Material UI in my code: const useStyles = makeStyle ...

Tips for extracting data from JSON values

My JSON Data Display let foodData = [{ meal_com_id: "1", name_company: "PeryCap", image: "https://shopgo.in/upload/1545849409-1518284057-Untitled-nn1.png", status: "1", description: "sdvaebfvhjaebfber itnwiuore tg5ykrgt wiretgi34 tgi3rgt ...

Exploring the variations in module definitions with requireJS

Struggling with requireJS right now. It's an AMD which means it's asynchronous. Typically, a module would be defined like this: define("some Name", ["./moduleOne"], function(moduleOne){ //this would be undefined moduleOne.whatEver(); v ...

Retrieving queries from a sibling component using react-query: A step-by-step guide

I have a question regarding how to refetch a query from another sibling component using react-query. Let's consider Component A: import {useQuery} from "react-query"; function ComponentA(){ const fetchData = async () => data //re ...

What is the best way to generate script code dynamically on an HTML page depending on the environment?

I am facing a challenge with my asp.net application. I need to insert a dynamic script into the html section, and this script's value must change depending on the environment (TEST, QA, etc.). To illustrate, here is the script where DisplayValue is th ...

Mobile devices have a fixed distance and center alignment on the horizontal timeline

I am attempting to create a horizontal timeline similar to this example: https://codepen.io/ritz078/pen/LGRWjE The issue I am facing is that I do not have specific dates (DD/MM/YYYY) but only ranges such as 1998-2002 or single years like 2009. This has ca ...