Tips for effectively integrating javascript and razor syntax in web development:

I am currently working with this code in my razor view and I need to assign values from Razor to some JavaScript variables.

Despite my efforts, the variables are not getting assigned any values.

var listPuntos =[];
    function onSelect(e) {
        var dataItem = this.dataSource.view()[e.item.index()];
        @{
            var proveedorID = 0;
            <text>proveedorID = dataItem.ProveedorID</text>
            var list = new UnitOfWork().PuntosVentaProveedorRepository.Get().Where(x => x.ProveedorID == proveedorID);
            proveedorID = 0;
            <text>listPuntos = list; </text>;
            <text>
                var displayText;
                $.each(listPuntos, function (key, value) {
                    if (displayText == undefined)
                        displayText = value.Nombre + ', ';
                    else
                        displayText = displayText + value.Nombre + ', ';
                });
                document.getElementById("puntos").value = displayText.slice(0,-2);
            </text>
        }

    }

Answer №1

Based on the given concrete example, a good way to start would be by minimizing the number of <text> blocks required. Instead, consider enclosing the shorter C# snippets with @{ … }, which can enhance readability and reduce confusion. For instance:

var listPuntos =[];
    function onSelect(e) {
        var dataItem = this.dataSource.view()[e.item.index()];
        @{ var proveedorID = 0; }
        proveedorID = dataItem.ProveedorID;
        @{ var list = new UnitOfWork().PuntosVentaProveedorRepository.Get().Where(x => x.ProveedorID == proveedorID); }
        proveedorID = 0;
        listPuntos = @Json.Encode(list);
        var displayText;
        $.each(listPuntos, function (key, value) {
            if (displayText == undefined)
                displayText = value.Nombre + ', ';
            else
                displayText = displayText + value.Nombre + ', ';
        });
        document.getElementById("points").value = displayText.slice(0,-2);
    }

To include a C# value in JavaScript code generated by the server, it must be encoded in JavaScript. One effective method is to convert it to JSON format, as demonstrated using Json.Encode. This conversion is illustrated by the line:

        listPoints = @Json.Encode(list);

Although Json.Encode was utilized here, feel free to choose any suitable JSON library that aligns with your project requirements.

Answer №2

It is important to separate your HTML code from your JavaScript code in order to maintain a clean and organized structure. Avoid calling server-side code directly from the View during loading. Instead, pass all necessary data via the model property in a suitable format such as JSON, and then populate any client-side lists from the values of that property.

var displayText;
$.each(listPuntos, function (key, value) {
    if (displayText == undefined)
        displayText = value.Nombre + ', ';
    else
        displayText = displayText + value.Nombre + ', ';
});
document.getElementById("puntos").value = displayText.slice(0,-2);

Move code snippets like the one above to the appropriate section, for example:

@section scripts
{
    <script>
    .....
    </script>
}

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

Using the useState hook will help avoid any crashes when running on IE11

I recently added a new repository to my GitHub account. The file dist/index.htm is causing Internet Explorer 11 to crash, displaying the error message: "unable to get property 'root' of undefined or null reference." This issue arises when I u ...

Missing RequestVerificationToken value when hiding HTML element using jQuery

I am encountering an issue with my ASP.NET MVC 4 form that involves checkboxes being used to show and hide certain HTML elements. When I initially visit the form page, the RequestVerificationToken value is correctly created as a hidden field. Some HTML ele ...

Error: JSON.parse encountered an unexpected token due to an invalid JSON format sent to the Backend

Let me provide some background: I've been working on setting up a basic Crud system with a Client/Server architecture. To streamline the process, I decided to create a multi-step form since some forms were getting lengthy. However, I encountered diff ...

Navigate from Product Listing to Product Details Page by utilizing JSON data with ReactJS

I have successfully retrieved the initial level of JSON Data, which consists of objects/Product List. My objective is to implement a functionality where clicking on the "View Details" button will redirect to the respective product detail page, similar to ...

What is the process for including an additional button in the DateTimePicker feature of material UI?

I'm currently utilizing DateTimePicker in my React application. https://i.sstatic.net/ShyTE.png I wish to incorporate a Clear button positioned to the left of the Cancel Button. import { MuiPickersUtilsProvider, DateTimePicker } from "@material-ui/ ...

Central data repository: various users

I am facing a challenge where I have one table containing initial data and multiple consumer applications operating on various machines within a local network. I am seeking advice on how to efficiently organize these applications in a way that each record ...

Achieving the functionality of keeping the search query box and alphabetical search options visible on the page even after performing a search and displaying the results can be done by

I have set up a PHP page with search query field and alphabetical search options. When submitting the query, the results are displayed on the same page; however, I would like the results to show in the same location as the alphabetical search. Currently, ...

Prevent ng-repeat from rendering the contents of my div

Currently, I am in the process of modifying a website for which I need AngularJS. I am trying to use the ng-repeat command to display some documentation on the site. However, whenever I add the ng-repeat within a div, it seems to "destroy" the layout and I ...

Are you ready to proceed to the next step?

I am looking for a solution to implement a confirmation alert in my HTML form. The form is submitting to itself, and I want to ask the user if they want to continue if any of the checkboxes on the form are checked. However, I only want to ask them once, n ...

What type of technology is typically utilized in creating functional platforms such as goDaddy, wix, and other web design websites?

I am currently working on a web development project that aims to allow users to edit webpages without needing any coding knowledge. Users with authorization will be able to modify not only the text but also various HTML tags on the page, similar to platfor ...

Automatically updating values in AngularJS

I currently have an array of dates stored in $scope.dates = [] ($scope.dates[0].date). My goal is to create a new array with durations that update automatically. $scope.dates[i].duration = Date.now() - $scope.dates[i].date. The objective is to display a ...

What is the best way to export a React Material-UI component with two separate styles objects in Material-UI V1?

We are currently utilizing material-ui version 1 and composing Higher Order Components (HOC) with the recompose utility. Our issue arises from having two separate styles objects - one defined within the component itself, and another general style object th ...

Is the tab not displaying correctly when using Bootstrap 5 button functionality?

With Bootstrap 5, I have a modal that contains two tabs for login and register. However, I am facing an issue where the tab is not displaying correctly based on the button click. The desired behavior is that clicking on the login button should activate th ...

Generate visual representations using Google charts and JSON data

I am looking for a way to retrieve and utilize a dataset for Google Charts from a separate JSON file. I attempted to use jQuery getJSON method but encountered issues. The goal is to have Google Viz utilize the JSON data to create a bar chart. Is there a ...

When I try to install dependencies with Hardhat, the "Typechain" folder does not appear in the directory

After installing all the dependencies, I noticed that the "typechain" folder was missing in the typescript hardhat. How can I retrieve it? Try running npm init Then, do npm install --save-dev hardhat Next, run npx hardaht You should see an option to se ...

Using ng-options to connect an array of objects to an ng-init attribute

Working on creating a select dropdown using ng-options to iterate over an array of objects and linking it to ng-init. However, running into an issue where the correct variable needs to be passed through ng-change as well. The current code is set up in a w ...

Total of the various components within an array

I'm new to programming and I'm trying to calculate the sum of all elements in an array. I've written this code, but it doesn't seem to be working properly. Can someone help me find my mistakes? function ArrayAdder(_array) { this.su ...

Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image usi ...

Absence of .NET Core in the Target Framework Options

I am currently using Visual Studio 2017 Enterprise and attempting to switch the target framework of a unit test project to .NET Core in order to utilize xUnit. However, I cannot locate it in the list of available frameworks. The available frameworks in my ...

A Guide to Uploading Multiple Images with Multer in NodeJs and ReactJs

My goal is to implement the functionality of uploading multiple images from my reactjs frontend using DropZone. I have successfully configured the backend to handle the upload process for multiple images, however, I am facing an issue where no images are g ...