Leveraging a Javascript variable within a C# code block

I've been attempting to retrieve a variable using JavaScript and then use it in my C# block, but it seems like it's impossible.

Here is my HTML code:

<select class="form-control" id="Category">
    @foreach (var item in Model.Categori)
    {
        <option value="@item.CategoriId">@item.CategoriName</option>
    }
</select>
<div id="Container"></div>

And this is the JavaScript code I'm using:

$('#Category').on('change', function (e) {
   $("#Container").append(`@foreach (var item in Model.YetkinlikKategorileri.Where(x => x.Id == $('#Category').val()))
   {
       <p>hello</p>
   }`);
});

Is it possible to achieve something like this? If not, is there another way?

Answer №1

Here is a code snippet that demonstrates the necessary steps:

<script> 
var data = [
        @foreach (var item in dataList)
        {
            @Html.Raw("'"+item+"',")
        }
    ];
    $('#Category').on('change', function (e) {
        var lst = data.find(/*Your condition*/);
        for (var i = 0; i < lst.length; i++) {
            $("#Content").append("<p>hello</p>" + data[i] + "<br/>");
        }
    };
</script>

dataList represents the data received from the server.

This method involves retrieving all the data from the server and storing it in the javascript data array, then creating lst by searching within the data array.

However, using AJAX would be a more efficient approach compared to this razor code implementation.

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

The MVC website is displaying incorrectly on the IE11 browser when accessed from IIS, but it appears correctly when accessed from the .NET IDE

Although my website works well in Chrome and Firefox, I encountered some issues in IE11 when accessed from IIS (however, it displays correctly on IE11 when accessed from the .NET IDE). The main Menu page appears to be using an incorrect version of Bootstra ...

Creating a single Vuetify expansion panel: A step-by-step guide

Is there a way to modify the Vuetify expansion panel so that only one panel can be open at a time? Currently, all panels can be closed which is causing issues. I would like the last opened panel to remain open. I also want to prevent closing the currently ...

Is there a way to effectively alter an object that has been assigned in a separate file?

Seeking Assistance: I am facing an issue in my current project where I need to store a javascript object in an external file and then export it using module.exports. The challenge now is that I want another file to be able to modify a specific value withi ...

Troubleshooting CSS Animation Failure in Internet Explorer 11

My mouse over / mouse out animation works perfectly in Firefox and Chrome, but it's not functioning in IE. Can anyone suggest why this might be happening when it was working fine before? var actual = 1; var over = 0; var over2 = 0; function scrol ...

The page fails to redirect to the intended page when provided with an incorrect URL

I am currently working with an Angular function that I have provided below. Function : 404.html file located in the root folder.</p> The issue I am encountering is that despite no errors appearing in the console, the URL in the address bar always ...

Encountering an unexpected or invalid token in line 1 after reinstallation of Windows can be a frustrating experience

Yesterday, my JavaScript file was running smoothly. However, after reinstalling Windows and Node, I'm encountering an error when trying to run the same JavaScript file today. $ node index.js C:\Users\<user-name>\Google Drive&bsol ...

Encountered difficulty accessing the controller ActionResult from JavaScript代码

Resolution: After thorough investigation, I successfully identified and resolved the issue. Surprisingly, it was not related to the Javascript or Controller code as initially anticipated. The root cause stemmed from a .dll file that was causing discrepanci ...

Tips for implementing a null check within the findAll() function

I am inquiring about the database and some parameters on the request body are optional. Can someone please guide me on how to determine if certain fields, like categoryId, are nullable and perform the where query based on that? var categoryId = req.body ...

List Sorting with VueJS Drag and Drop功能

I'm currently utilizing the Vue.Draggable plugin to create a draggable list feature. I have a sorted computed property being passed in this way: data(){ return { paymentMethods: [ { name: 'stripe', Dindex: 0, state: 2 }, { n ...

Issue with CSS: 200vw not scaling correctly for mobile devices

I'm attempting to create a horizontal slide effect between two div elements, so here is the HTML code: <div id="container"> <div class="viewport-1"> <div class="inner-div"> <h1>Viewport background 1</h1></ ...

Error: material not being loaded by objloader

I recently started working with Three.js and encountered an issue while loading an obj object into my scene. The object loads successfully, but the materials are not provided by the MTLLoader. I'm unsure if my object is broken or if there is an issue ...

Awaiting the outcome of the Typescript map function is non-existent

In order to find the subcategories of an article, I am utilizing a many-to-many relationship with TypeOrm that requires Ids. However, I encountered an issue where the map function is not properly waiting to push the results into the array. Below is the c ...

Obtain the text content of a WebElement using the Selenium Driver in JavaScript

Is there a way to verify if the element I've selected by its id has the expected text content? var driver = require('selenium-webdriver'); var By = driver.By; var elem = this.driver.findElement(By.id('my_id')); assert.equal(elem. ...

Empty results received from MongoDB queries executed within an asynchronous loop

I'm encountering an issue where I have a list of IDs that I need to query Mongo with in a for loop, but it always returns an empty []. Initially, the queries were returning promises, so I switched from using forEach to a standard for loop as shown her ...

"PHP and Javascript Validation Library: Building Confidence in Your Data

Looking for a PHP form validation library that can work independently outside of any PHP framework? It should be able to handle basic validations like checking for empty fields, using regex, validating email addresses, and alphanumeric characters. Ideally, ...

Designing the appearance of a table based on the information it holds

I came across a table that I need help with: http://jsfiddle.net/UfhVc/1/ My objectives are: To apply the same style to all rows with identical IDs To highlight variations in each row among those with the same ID Currently, I am struggling to determine ...

Resolving the 'Uncaught TypeError: number is not a function error' and tackling the 'Failed to load resource' issue

What is causing the error in the code? var images = ['/test/img/Gallery/large/4cba0c8a-4acc-4f4a-9d71-0a444afdf48d.jpg','/test/img/Gallery/large/4cba0ca8-2158-41af-829a-0a444afdf48d.jpg','/test/img/Gallery/large/4cbc549a-5228-433f ...

At what stage of the Angular JS application life cycle is this code being loaded?

I am facing a difficult issue with the timing of Angular JS life cycle in relation to the code snippet below. There seems to be a random occurrence where controllers dependent on this code are loaded before it, leading to errors. Even after multiple atte ...

"No location information is available" regardless of the input provided

Despite my efforts to utilize intl for formatting purposes, I consistently encounter the error message: ReferenceError: No locale data has been provided for this object yet I've experimented with various approaches such as: new Intl.NumberFormat( ...

Calculating the Bounding Box of SVG Group Elements

Today I encountered a puzzling scenario involving bounding box calculations, and it seems that I have yet to fully understand the situation. To clarify, a bounding box is described as the smallest box in which an untransformed element can fit within. I h ...