Requesting information from a model using a JavaScript variable in a cshtml file in an ASP.NET application

Is there a way to use a JavaScript variable to retrieve a specific item from an array stored in a model?

Below is a code snippet:

function CreateCategoryList() 
    {
        var limit = @(Model.CategoriesCount.ToString());

        for (i=0; i<limit; i++)
        {
            var category = '<div class="CategoryItem">' + '@(Model.CategoryList[i].Name.ToString())' + '</div>';                
            $("#CategoriesPopup").append(category);
        }
        alert($(".CategoryItem:first").text());
    }

I'm trying to access the i-th item in Model.CategoryList using the i variable in the for loop. Can anyone help with this?

Answer №1

Razor does not run on the client side, so the code snippet you provided is not valid.

An easy solution is to save the entire array as a JavaScript variable on the client side by using serialization. In the example below, I have used Json.NET.

I recommend investigating what is executed on the server versus the client side. Understanding this distinction will aid you in writing Views.

function CreateCategoryList() 
{
    var limit = @(Model.CategoriesCount.ToString());
    var clientSideArray = JSON.parse('@(JsonConvert.SerializeObject(Model.CategoryList))');

    for (i=0; i<limit; i++)
    {
        var category = '<div class="CategoryItem">' + clientSideArray[i] + '</div>';                
        $("#CategoriesPopup").append(category);
    }
    alert($(".CategoryItem:first").text());
}

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

Error has occurred: Unable to assign a value to an undefined property using axios

Within my Vue.js component, I am utilizing axios to fetch a JSON array consisting of `joke` objects: <template> <div id="show-jokes-all"> <h2>Showing all jokes</h2> <div v-for="joke in jokes"> ...

Guide on building a Vue Js input name field with string-variable schema

I have a project using VueJs and I am looking to extract JavaScript variables to create hidden fields. My goal is to set the name of the field based on the index of the variable, following a zig-zag naming schema. For example: <input type="text" nam ...

Prevent the <a> tag href attribute from functioning with jQuery

I came across this code snippet: <script type="text/javascript"> $(document).ready(function() { $("#thang").load("http://www.yahoo.com"); $(".SmoothLink").click( function() { $("#thang").fadeOut(); $("#thang").load( ...

The term 'MapEditServiceConfig' is being incorrectly utilized as a value in this context, even though it is meant to refer to a type

Why am I receiving an error for MapEditServiceConfig, where it refers to a type? Also, what does MapEditServiceConfig {} represent as an interface, and what is the significance of these brackets? export interface MapEditServiceConfig extends AppCredenti ...

Transferring information through AJAX and fetching through PHP

Below is my current AJAX code setup: optionScope.data().stage = 'b'; $.ajax({ url: "functions/contact.php", type: "post", data: {'stage': optionScope.data().stage}, success: function(data, status) { ...

The notification bar only makes an appearance when necessary

I am currently working on a dynamic piece of code that sends a request to PHP and receives a response. The goal is for the notification bar to fadeIn() and fadeOut() every time there is a new notification. However, I have encountered an issue where the n ...

An unexpected identifier error occurred following an Ajax request

Below is the HTML code that I am working with: <div id="texttheory" class="centertext">'. $short .' </div>'; <button id="thbutton" class="theory_button" onclick="javascript:changetheory('.$long.')"> <im ...

Is there a way to extract just the first line or n characters from a JSON file without having to download the entire dataset?

I am looking to extract specific information from a large JSON file that is 450 KB in size. However, I do not need to download the entire JSON file as I only require certain characters or lines from it. Is there a way to read n characters or line by line ...

react component not displaying image

I must admit, this might be a silly question but I'm just starting out in web development. My goal is to create a clickable image component that redirects to another page on the website. However, despite not encountering any errors, the image is not ...

Fill up a data repository with the names and corresponding Project IDs

I am tasked with developing a project management system using C#. My inquiry revolves around how to populate a dropdown menu with project names while keeping the project ID hidden. This way, when I need to add a task, I can easily choose the project to wh ...

Tips for creating a user-friendly message using the iCalendar format

Imagine a scenario where we encounter a recurrence rule such as the following: RRULE:FREQ=MONTHLY;BYDAY=-2FR;COUNT=7 I am curious about how one might transform the information in the RRULE into user-friendly text, for example: occurs every month on the ...

Implementing a persistent header on a WordPress site with Beaver Builder

My website URL is: . I have chosen to use beaver builder for building and designing my website. I am in need of a fixed header that can display over the top of the header image. Here is the code snippet that I currently have: <div id="header">html ...

Ways to access an element within a function triggered by an event listener

Is there a way to dynamically add a class to an element with a specific class when it is clicked? Specifically, I want to target elements with the "date" class and give them an additional class upon click. $(".date").on("click", function() { // Code t ...

Trouble with retrieving dates in ISO format

My collection stores the date of birth field in ISO format, for example: ISODate("1980-01-01T20:20:19.198Z") However, when I use a date time picker on my HTML page, it displays the date like this: 01/01/1980 Unfortunately, when querying for the date of ...

Can you use Stryker.NET to specifically exclude internal methods and constructors from mutation testing?

When referencing Ignore-Methods in the documentation for Stryker.NET, it is possible to specify methods and/or constructors that should be excluded from mutation, as shown in this example: "stryker-config": { "ignore-methods": [ ...

What is the maximum number of requests that Node-Express can send simultaneously?

Currently, I am facing a challenge with my script that involves fetching 25,000 records from AWS Athena, a PrestoDB Relational SQL Database. For each of these records, I need to make a request to Athena and then another request to my Redis Cluster once the ...

Elements that possess identical class attributes yet exhibit dynamic behavior

I'm currently facing challenges with dynamically generated elements. I am working on a page for my website that will show a list of users (data provided by the controller). Each user is represented within a div, containing two h3 tags displaying the u ...

Personalized DataAnnotation and Models for Viewing

My custom DataAnnotation works perfectly, but I encountered an issue when using a ViewModel instead of the actual Model. When I use a Model, the data annotation generates: <label class="tooltip" for="title">Enter a title.</label> However, wh ...

The significance of Token Details in Tokbox

I'm currently working on developing a video chat platform that caters to various user roles - some may just observe while others actively participate in calls. I've been exploring the capabilities of the Tokbox Api () which allows metadata to be ...

Issue with event listener not functioning properly with dynamically created content using AJAX (only using vanilla JavaScript

I used pure javascript AJAX to dynamically load content into the "test" div. However, when I try to click on a child div at index 6, an alert box is not being displayed as expected. How can I fix the issue with the click event not working? The gets functi ...