Storing the .NET Framework viewmodel in its own individual Javascript file

I have a question about structuring my design for SoC (Separation of Concerns). I currently have the following files:

  • testController.cs
  • testViewModel.cs
  • testView.cshtml
  • testScript.js

Currently, I generate data in the controller, populate the testViewModel, and pass it to the Razor view. Inside the Razor view, I can directly use the data like this:

<script>
    var someVariable = @Model.someVariable;
</script>

Everything works fine until I try to move my JavaScript code into a separate file.

What is the best way to access the data in a variable that is located in a JavaScript file?

That's my main question. Additionally, once I solve this issue, I'd like to incorporate VueJs in a separate file as well.

However, I'm unsure how to pass data from the Razor view to the Vue data variable.

What would be the best practice for achieving this?

Answer №1

There isn't a one-size-fits-all "best practice" for this situation as different approaches work better in different contexts. Personally, I find the "revealing module pattern" with IIFEs to be a useful method. Here's an example:

CustomScript.js

var CustomModule = (function () {
    var customVariable = null;

    return {
        // externalVariable will be provided by the caller
        initialize: function (externalVariable) {
            customVariable = externalVariable;
        }
    };
})();

Then in the HTML file:

MyPage.html

<!-- include your CustomScript.js file -->

<!-- other content -->

<script>
    CustomModule.initialize(@Model.externalVariable);
</script>

This pattern can also be adapted to set up Vue using the parameter(s) passed to CustomModule.initialize().

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

Leveraging jQuery to implement onclick functionality within a Jinja2 loop

I'm currently working with Python, Flask, and Jinja2. When using a for loop, I want to be able to click on the {{ place.place_photo }} element to toggle its details. Initially, I had it functioning correctly but ran into an issue where clicking on on ...

Develop a Vue.js module that incorporates SCSS styling for enhanced customization

I'm looking to develop an npm module for sharing across various projects in our repository. The "library" I've created includes basic vue.js components and some SCSS styles. I want to be able to easily reuse these elements. One issue I've e ...

Tips for closing 2 models in a React application

Currently, I am working on a project using ReactJs. One of the functionalities I am implementing is generating a user's gallery when the user clicks on their avatar. To achieve this, I am utilizing the react-grid-gallery package along with semantic ui ...

Load a page and sprinkle some contents with a slide effect

I am brand new to jQuery and just starting out, so please excuse me if this question seems basic or silly. I would like the header and footer of my page to stay in place while the center content slides in from the right side when the page loads. This websi ...

A guide to efficiently passing props in a Vue.js application connected to Express with MongoDB

I am in the process of creating a simple chat application using Vue.js, Node, Express, and MongoDB. The app starts with a welcome page where users can input their names (refer to: Welcome.vue). After entering their name, users are directed to Posts.vue, pa ...

The Problem of Restoring Column Height in Tabulator 4.6.3 Filters

The Issue After activating and deactivating header filters, the column height does not return to its original state. Is this the expected behavior? Is there a way to reset the column height? Check out this JS Fiddle example: https://jsfiddle.net/birukt ...

What is the process for extending the timeout of my ApplicationCookie in Identity 2.0?

Is there a way to extend the authentication timeout of a cookie during a specific web request? I am working with an Angular app on top of my MVC 5 project and I need it to maintain my server session alive between requests. While I have successfully impleme ...

Parsing Problem---Is there a Parsing Error?

My code includes a function that calculates the total of cells and then displays it in a textbox: function UpdateTotal() { var total = parseFloat('0.0'); $("#<%= gvParts.ClientID %>").find("tr").not(".tblResultsHeader").each(funct ...

What sets Fetch apart from ajax and XMLHttpRequest that makes it impressively faster?

Over the past few days, I have been working on optimizing a client table for a project. The table contains over 10k clients, and as a result, it was taking a long time to load. The front-end team had implemented pagination, filters, and reordering, which ...

Can a function be passed to the URL field in an AJAX request?

Can a function be passed to the url field in an ajax call? I am looking to dynamically change the url being used in the ajax call. function generateURL(){} $.ajax({ url: generateURL, context: document.body, success: function(){ $(this).addCla ...

Combine all div elements to create a unified image and then proceed to save it as a jpg file before uploading to the server

These are the divs below: <div style="width:800px; height:420px; position:absolute; top:0px; left:0px; z-index:10; background-image: url('https://3t27ch3qjjn74dw66o1as187-wpengine.netdna-ssl.com/wp-content/uploads/2016/05/052516-800x420-vege-Wallp ...

Learn the process of adding transformation to an SVG path element

I have an SVG image loaded in my HTML file and I am trying to rotate one of its path elements, but I'm having trouble figuring out how to do it. The code snippet provided below is not working as expected. Can anyone provide guidance on how to achieve ...

What are the steps to reset the Firebase server in order to allow the deployment of functions

After using firebase deploy --only functions, an error appeared in my React code and I had to use control-C to stop the deployment on my Mac. Now, when attempting to redeploy to Google servers, the following error is encountered: firebase.js -> build/f ...

There is a necessary pause needed between carrying out two statements

I am currently working with extjs 4.2 and I have encountered a situation where I am loading the store object in the following manner: var userDetailStore = Ext.create('Ext.data.Store', { model: 'Person.DetailsModel', autoLoad: ...

Utilizing jQuery Mobile - Dividing content across multiple HTML files

In the process of developing a web application utilizing jQuery and jQuery mobile, I am aiming to display various pages. Given that the corresponding html-markup may become lengthy, I am interested in dividing the html into separate files. For instance: & ...

angular corresponding vue binding="$props"

If I wanted to take a shortcut, I could utilize v-bind="$props" to dynamically set key values as shown in the sample below : <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> ...

What is the best way to capture GotError [HTTPError]: When the response code 404 (Not Found) occurs in a nodejs

If the URL provided is incorrect and the Got module raises a HTTPError, how can I properly catch the error? Using try-catch does not seem to be effective in this situation. const got = require('got'); got(`https://www.wrongurl.com`) ...

Ordering a string of whole numbers using JavaScript

I'm currently working on a form that takes a string of numbers, splits them at each semi colon and space, sorts the numbers, and then displays the sorted list. However, when I click the button, the value in the text box doesn't get posted. Can ...

Leveraging $last in Angular for obtaining the final visible element with ng-show

My ng-repeat container div contains multiple images, each with a corresponding div next to it. Using $last, I can make sure only the div of the final image is visible after all images. However, I also have a filter button on the page that hides certain im ...

Using dangerouslySetInnerHTML in React within a Fragment

In my current project, I have a specific requirement where I need to format text in React and also include HTML rendering. Here's an example of what I'm trying to accomplish: import React, {Fragment} from "react"; import {renderToString} from " ...