Include performers in a roster for DVD collection

Currently, I am facing an issue with adding multiple actors to a DVD object. Despite my efforts to use JavaScript to dynamically create text boxes for each actor, only the first one is being saved. Do you have any advice or suggestions on how to resolve this?

Below is the code snippet in the view related to the actor list:

<div id="actorsContainer">
        <div class="form-group">
            @Html.LabelFor(model => model.dvd.ActorList, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.dvd.ActorList, new { htmlAttributes = new { @class = "form-control", id = "actors", name = "actors[]" } })
                <input type="button" class="btn-sm btn-default col-md-2" id="addActor" value="+" />
                @Html.ValidationMessageFor(model => model.dvd.ActorList, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>

I have also included the JavaScript code that I am currently using:

<script>
    document.getElementById("addActor").onclick = function () {
        var div = document.getElementById("actorsContainer");
        var input = document.createElement("input");
        input.type = "text";
        input.name = "actors[]";
        div.appendChild(document.createElement("br"));
        div.appendChild(input);
    }
</script>

In addition, here is the code for the controller that may be relevant to this issue:

        [HttpGet]
    public ActionResult AddDVD()
    {
        DVDListVM vm = new DVDListVM();

        return View(vm);
    }

    [HttpPost]
    public ActionResult AddDVD(DVDListVM model)
    {
        if (ModelState.IsValid)
        {
            DVD newDVD = new DVD();

            // Setting properties of newDVD

            _dvdManager.AddDVD(newDVD);

            return RedirectToAction("Collection");
        }
        else
        {
            return View(model);
        }
    }

Answer №1

To display a collection called ActorList, you need to generate an input for each item in the collection using the following code:

@for (int x = 0; x < model.movie.ActorList.Count; x++)
{
    @Html.TextBoxFor(model => model.movie.ActorList[x], new { htmlAttributes = new { @class = "form-control"} })
}

The id and name attributes are not manually assigned as razor will automatically generate values for them.

If you wish to dynamically create inputs, you can analyze how index handling works for collections in the rendered HTML by Razor. In my case with ASP.NET MVC Core, here is an example of how an email input within a collection appears in the HTML:

<input name="EmailAddresses[1].EmailAddress" class="form-control emailInputAddress" id="EmailAddresses_1__EmailAddress" type="email" value="">

To dynamically add inputs, I extract the current index, increment it, and then duplicate the element with the updated index.

var newEmailInput = $(".emailInput:last").clone(true)[0].outerHTML;
    // get current index generated by razor and increase it
    var newEmailInputIndex = newEmailInput.match(/(\[([^\]]+)\])/i)[0].match(/\d+/i)[0];
    newEmailInputIndex++;
    newEmailInput = newEmailInput.replace(/(\[([^\]]+)\])/ig, "[" + newEmailInputIndex + "]")
                            .replace(/(_([^_]+)__)/ig, "_" + newEmailInputIndex + "__");

    $(this.lastEmailInput).after(newEmailInput);

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

Sending information to a dialog box

I'm facing a challenge with my button that triggers a modal. Although the button works fine, I now need to figure out how to pass data from the button to a specific field within the modal. Here is the HTML code: <input type=button value='Add ...

Show or hide comment sections using jQuery on a single webpage

Currently, I have implemented a script to toggle the visibility of comments on several WordPress-based websites. The script works well on most sites, but I am facing an issue with a site using the Hero theme. On the index pages, the theme displays content ...

Using AngularJS: Implementing asynchronous $http.jsonp request through a service

I am currently developing a straightforward application that involves the following steps: 1. The user provides 2 parameters and clicks a button 2. Angular communicates with an external JAVA Servlet that sends back JSON data 3. The application displays the ...

VueJs seems to be having trouble with vertical chat scrolling functionality

I need assistance with implementing chat scrolling in my VUE JS application. I would like the messages to automatically scroll to the bottom of the page each time a new message is received or when the page loads. Currently, I have a function that contains ...

Utilize JSX to dynamically insert HTML tags onto a webpage

I am trying to achieve a specific task in JSX, where I want to identify all strings enclosed within delimiters :; and wrap them with HTML Mark tags to highlight them. However, the current implementation is not rendering the tags as expected. Is there a sol ...

Displaying PHP content using JavaScript classes

I have a popup feature implemented in JavaScript and all the necessary scripts added to my HTML page. I am attempting to load a PHP page in the popup when the submit button of my form is clicked. The popup is functioning correctly for buttons like the one ...

Ways to invoke a function within a React Material-UI component

Currently, I am in the process of setting up a chat system that allows users to add emojis. To achieve this feature, I have devised a function that produces a component containing both text and an image. Here is the function I have implemented: test: fu ...

Managing time-intensive web service operations using JavaScript callbacks

One of the operations in my Web application involves a function that returns a value, which then needs to be passed to a web service method running separately from the application. This web service operation takes some time to complete and therefore must r ...

Is there a way to transform a JSON object into a custom JavaScript file format that I can define myself?

I have a JSON object structured as follows: { APP_NAME: "Test App", APP_TITLE: "Hello World" } My goal is to transform this JSON object into a JavaScript file for download. The desired format of the file should resemble the follo ...

Update the div and table without waiting for a specific time interval when an event happens

Currently, I have a table within a div that includes both editing and deleting functionality for records. After deleting a record, I want the table to be automatically updated with fresh data without having to reload the page. Can someone please provide me ...

JavaScript code designed specifically for Chrome browser that enables dragging functionality for div elements, unfortunately, it does not function on Firefox

Do you have a moment to help me with a small issue? I created a script that allows you to change the position of a div by dragging it. The script works perfectly in Chrome, but unfortunately, it's not working when I try it in Firefox. var h = windo ...

Troubleshooting problem with model binding in ASP.NET Web API

I've encountered an unusual problem in my WEB API project. Below is a snippet of my project's code: Model Class: [DataContract] public class StudentInfo { [Key] [DataMember] [StringLength(20)] ...

Ways to decrease the time it takes for data to load after the initial browser visit

In our project, we have multiple large solutions, each containing around 40 individual projects such as class libraries and nested websites. It currently takes approximately 2 minutes to perform a full rebuild of all projects. Here are some specifications ...

The feature of scrolling to a specific element within a bootstrap modal is not functioning as expected

I recently encountered an issue while using a Bootstrap modal. The problem arose when I tried to scroll to a specific element within the modal, but my code didn't produce the desired results. $('#centralModalLg').on('show.bs.modal&apo ...

Automatically scrolling a div to the bottom in a React component

I am currently working on developing a chat application for my school project, and I would like to implement the feature that automatically scrolls to the bottom of the chat window. Despite trying various solutions and encountering React errors, I have not ...

Guide on how to toggle disabled input text box upon checking checkbox using JavaScript

When the checkbox next to the appended text box is checked, I want to disable that text box. The hard-coded text box is already disabled when its checkbox is checked. You can see the actual outcome by running the code snippet or check out the screenshots b ...

Analyzing the DOM content loading time for web pages generated using AJAX technology

When analyzing website performance, I rely on window.performance.timing. However, this method falls short when it comes to measuring the performance of webpages loaded through ajax calls. For instance, websites built with frameworks like angularjs often lo ...

How do I choose and click on a JavaScript link using Watir-Webdriver?

For my mobile webapp, I am attempting to create a test using cucumber+watir-webdriver. However, I am encountering difficulty when trying to select a specific link on a splash message. The link I need to choose is <a class="btn" href="#">Close button ...

The URL in an AJAX request includes a repeating fragment due to a variable being passed within it

const templatePath = envVars.rootTemplateFolder + $(this).attr('link'); console.log("templatePath : ", templatePath); $.ajax({ method: "GET", url: templatePath, context: this, success : function(result){ ...

What is the reason for the binding event being triggered following the re-render of the setstate?

The Test component has a state of num. This component is designed to increase the value of num by 1 when a button is clicked. The button is linked to a self-increment method, and the keyup event is also connected to this method. When the method is triggere ...