Using a for loop in JavaScript to dynamically display TextBoxFor(model=> model[i].prop) in an MVC application

I need some help getting this code to function correctly:

$('#ddl').change(function () {

            $('#cont').html('');
            var count = getCount($('#ddl').val())
            for (var i = 0; i < count ; i++) {
                var html = '<div class="display-row">' +
                '<div class="display-label">' +
                'Value:' +
                '</div>' +
                '<div class="display-field">' +
                'From: @Html.TextBoxFor(model => model[i].From) To:@Html.TextBoxFor(model => model[i].To)' +
            '@Html.ValidationMessageFor(model => model[i].To)' +
                    '</div>' +
                '</div>';
                $('#cont').append(html);
            }

        });

I am having trouble accessing the value of i for model[i] inside the JavaScript loop.

Can anyone suggest a way to achieve that?

Answer №1

"I need to retrieve the value of i for model[i] within a JavaScript loop."

If you require this, you can initiate an ajax request to fetch your model as a JSON object. Subsequently, iterate over your list and perform required actions.

In your controller, establish an action method that will provide a list of your models:

return json(your model list);

Then in JavaScript:

$.post(url, {}, function(data){
    for(var i = 0; i < data.length; ++i) {
    }

});

Edit: When utilizing

@Html.TextBoxFor(model => model[i].Od)
on the server-side, the generated HTML will be as follows:

<input type="text" name="[i].Od" data-val="true" data-val-required="validationMessage" />

You can manually create these tags and usually place them within a form. For validation purposes, you may follow these steps:

//Remove current form validation information
$("form")
    .removeData("validator")
    .removeData("unobtrusiveValidation");

//Parse the form again
$.validator
    .unobtrusive
    .parse("form");

(last code reference from this post)

Answer №2

Attempting to accomplish this task in the manner described is not feasible. ASP.NET operates on the server side, while JavaScript functions solely within the web browser environment.

Answer №3

When working with ASP.net, it is important to note that the server-side code runs before any Javascript code. This means that when the Javascript code is executed, the page is already rendered as text and you cannot directly access model[i]. To work around this limitation, there are two options available:

  1. If your model is small, consider having the server-side code generate a string containing a JavaScript array from the model and then have the JavaScript iterate through this array once the page is loaded.

  2. For larger models or data sets, you can create a method in your controller that returns JSON data. Your JavaScript code can then make an AJAX call to this method to fetch the necessary data.

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

Switching from using jQuery to Mootools in a short script that helps to balance the heights of

I have a simple script that I frequently use in jQuery to make boxes equal heights. Now, I need to convert it to mootools for a new project where the boxes will be floated left at thirds using style sheets. <div id="box1" class="equals">content he ...

If Django recognizes a form class within a div tag

Just a quick question. I'm trying to trigger a form submission using AJAX. <body> <div id="head"><a class="button">CLICK</a></head> - maybe above the head <div id="content"><a class="button">CLICK</a>&l ...

What causes the updated value to be appended to an array when using the spread operator to modify an existing property's value?

In my state, I have an array of objects: const initialState=[{a:1},{b:2},{c:{d:3}}] const [state,setState]=useState(initialState) My goal is to modify the value of b to 5 within my event handler: function changeBToFive() { setState((state) => [ ...

"Troubleshooting Error: When accessing a property in AngularJS,

My goal is to retrieve a date value. However, I encounter an error message saying 'Cannot read property 'NTLI' of undefined' whenever the checkbox is unchecked and the date picker is invisible. Strangely enough, everything works fine wh ...

Troubleshooting Selenium JS: Challenges with Locating Elements Across Pages

I'm facing a challenge in accessing elements on pages other than the main page in my electron app. Although there are multiple elements that load when the app starts, I can only interact with elements on the initial page. I believe the issue lies in h ...

Removing the gap between the clicked point and the draw point in Html5 canvas

To better understand my issue, please refer to the image linked below: In the image, you can see that when I scroll down and click on the canvas to point a position, it creates space between the clicked point and where the line is drawn. Below is the cod ...

Mastering the implementation of owl-carousel in React.js

I'm currently working on a project that involves utilizing the react framework. My intention is to incorporate the owl-carousel, however, I've encountered issues as it fails to function properly. The following error keeps popping up: OwlCarousel ...

Is the required attribute for form submission in Material UI not verifying in another file?

It seems that I may be importing incorrectly because a required field does not display a "please fill in this field" popover when attempting to submit a form. The imported classes are as follows: import * as React from 'react' import FormContro ...

callback triggering state change

This particular member function is responsible for populating a folder_structure object with fabricated data asynchronously: fake(folders_: number, progress_callback_: (progress_: number) => void = (progress_: number) => null): Promise<boolean ...

Leveraging LINQ to JSON for extracting distinct elements from a collection

Having trouble organizing a list of objects/values from a JSON feed using LINQ? Here is what my JSON feed looks like: { "Project":[ { "ID":"XY1212", "Name":"Some Name", "Description":"U.S. No 2 Diesel Retail Prices", ...

Using jQuery functions like closest(), find(), and children(), it is possible to target and retrieve the sibling of a specific parent

Having trouble determining the URL of a using .closest, .find and potentially other jQuery methods. The webpage structure is as follows: ul ul ul.good li ... li li <a href="/findme">findme</a> ul . ...

Can someone please explain how I can implement a multi-submenu feature using JavaScript?

HTML CODES: <header> <nav> <ul> <li class="asmenu"><a href="#">Menu1 <i class="fa fa-caret-down"></i></a> <ul class="submenu deact ...

What is the best way to instantiate a dynamic object within a literal?

I am dealing with an object that contains multiple fields, mainly consisting of constant string values. However, I also need to incorporate a variable that is determined by the current state. const {order} = this.state; myObject={{ fieldA: 2, fiel ...

Issue with Angular ng-model not functioning as expected within ng-repeat block

Encountering an issue when trying to bind Json data into ng-model within ng-repeat. html : <div ng-controller="Ctrl"> <div> <table> <th> <td>add</td> <td>ed ...

What is the ternary operation syntax for setting the img src attribute in Angular 8?

My data includes a property called "photo" which can either have a file name or be empty. For instance, it could be "steve.jpg" or just an empty string if Steve does not have a photo. In React JSX, I know how to use a ternary operator with the "photo" va ...

Identifying the FireOS version using JavaScript

Can JavaScript be used to determine the version of FireOS that a Kindle device is running when accessing your website? ...

What is causing the unexpected behavior of deferred.resolve in the q manual?

I can't seem to grasp this concept and it might be a silly question. Let's analyze the code snippet below: function throwError() { throw Error("can't touch this."); } var def = q.defer(); def.promise.then( function() { co ...

Learn how to easily toggle table column text visibility with a simple click

I have a working Angular 9 application where I've implemented a custom table to showcase the data. Upon clicking on a column, it triggers a custom modal dialog. The unique feature of my setup is that multiple dialog modals can be opened simultaneously ...

Can a hyperlink open multiple links at the same time when hovered over?

Can two links be opened in the same hyperlink when hovered over? ...

Retrieve the id of the clicked hyperlink and then send it to JQuery

<a class = "link" href="#" id = "one"> <div class="hidden_content" id = "secret_one" style = "display: none;"> <p>This information is confidential</p> </div> <a class = "link" href="#" id = "two" style = "display: non ...