Incorporate a Javascript session into MVC 4 Razor for enhanced functionality

I am currently developing an application that allows users to upload files. Before uploading the file, I need to configure the file storage settings. The first step is to read the first ten rows of the file and display them to the user. The user can then provide the necessary configuration, and I will proceed with uploading the file.

I have attempted the following approach:

<script>
document.getElementById('file').addEventListener('change', readSingleFile, false);
function readSingleFile(evt) {
    var FileBlock = "";   
    var contents="";
    var f = evt.target.files[0];
    if (f) {
        var r = new FileReader();
        r.onload = function (e) {
            contents = e.target.result;
            var Rows = contents.toString().split("\n", 10);
            FileBlock = Rows[0];
             for (var i = 1 ; i < Rows.length; i++) {
                 FileBlock += "|" + Rows[i];
             }
             alert(contents);

            @{
                Session["Test"] = @:contents+"";
             }

            OpenDockPanelBySumbitForm("ImporterPanel", "form",FileBlock);
            Hide_ContentZone_Panel();
        }
        r.readAsText(f);      
    } else {
        alert("Failed to load file");
    }
}

I have encountered an issue with this piece of code.

@{
   Session["Test"] = @:contents+"";
 }

If anyone has suggestions or can provide assistance, I would greatly appreciate it. Thank you for your participation.

Answer №1

Server-side dynamic functionality in Asp.net can be achieved with JavaScript. While JavaScript cannot directly assign values to variables based on the server, hidden variables can be utilized for this purpose;

http://example.com/image123.png

<input type="hidden" id="hdnsession" name="sessionData" value=" @Model.session??"" " />
public ActionResult example(string sessionData){
Session["Example"] = sessionData;
ViewBag.session = Session["Example"];
return View();
}

Answer №2

I discovered that there is a limitation in accessing Javascript variables from C# and vice versa. This is because C# code is compiled first before Javascript, resulting in C# not being able to see Javascript code. However, the reverse is possible.

One workaround is to relocate your script to a different folder, such as -plugins- to ensure that it is compiled first.

Check out the source here

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

What is the best approach in JavaScript to compare and modify properties in two arrays of objects with efficiency?

Here's a method I have written in an Ecma 6 component (Salesforce Lightning Web Components for anyone interested). I am sharing it here because this is more focused on JavaScript rather than LWC. Do you think this is the optimal approach to solve this ...

What is the best way to display two radio buttons side by side in HTML?

Looking at my HTML form in this JSFiddle link, you'll see that when the PROCESS button is clicked, a form with two radio buttons appears. Currently, they are displayed vertically, with the female radio button appearing below the male radio button. I& ...

The error message "writeUserData is not defined" is indicating that there is an undefined variable in the react code

I'm still learning React and I've been working on a new function: This is my code in summary: class Signup extends Component { constructor(props) { super(props); } componentDidMount() { } writeUserData = (userId, username, email) => ...

Displaying an array within a method using Vue.js

As a complete newcomer to Vue, I wanted to experiment with methods a bit. Specifically, I attempted to print out an array of strings using the following method: printStringArray(objectWithArray) { i = 0; s = ''; while(i < ob ...

Redirecting to another page with a simple link is not recommended

Once the user successfully logs in, I redirect them to the dashboard. Everything was working fine until I deployed it using tomcat. Now the URL is http://localhost:8080/myWar/ So when I use this: window.location.href = "/dashboard"; it redirects to ht ...

When I toggle the div to close on mobile, I want it to show on desktop

My attempt at creating a toggle button to hide and show content was not successful. I struggle with coding in Javascript/Jquery. In the desktop view, the description displays perfectly (see image here), but in mobile view, there is a button to toggle hidi ...

What's the better approach for creating Maps and Sets in ES6: relying on a compiler or leveraging syntactic sugar?

It has always baffled me why we are unable to write ES6 Maps in the following way: new Map({ ['ArrayAsKey']: {foo:bar} }) Is there a workaround for this limitation? Or perhaps a technique that enhances the experience of utilizing these mode ...

Using Jquery, insert a line break when a specific character is entered in a text area by pressing the Enter button

$('.text-description').keyup(function () { var count = $(this).val().length; if(count == 63){ //insert line break here } }); When the character count reaches 63, including spaces, I want the cursor to move to the next line (sim ...

Issue encountered when trying to deserialize an object with json.net

Using json.net for deserializing JSON to a list. I am encountering the following error: Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: [. Path 'data', line 1, position 9.' This is how my ...

Having four videos displayed on one webpage can cause the browser to function at a slower

I have videos that are around 30 seconds long and 15mbs. I'm wondering if it's feasible to include them on a page or if I should opt for cover images instead. I would like to use the video as a separator similar to the design showcased at Does a ...

Tips for resolving the chakra-ui theme issue with loading input background

I've been working on applying a theme to my Next.js app using chakra-ui, but I've been facing an issue that I can't seem to resolve. Currently, when the /form route is loaded, the theme is set to light. After changing it to dark, the theme i ...

A guide to securely retrieving data from the Hono API endpoint using type safety within a Next.js application

Currently, I am using Hono as my API endpoint with Bun. Now, I am working on a new app with Next.js and I want to ensure type safety when fetching data from my API. I believe I can accomplish this through RPC. However, I am unable to locate AppType mention ...

An unusual phenomenon in the controller hierarchy causing issues with accessing the parent scope in AngularJS

Recently delving into the world of angularjs, I encountered something perplexing that seemed like a glitch in the controller hierarchy when it comes to accessing the parent scope. Here are two code snippets that I believed should both function properly bas ...

What steps can be taken to have Eslint/Prettier report errors and warnings within a CI environment?

Recently, I encountered an issue with my Vue app where I am using Eslint with Prettier. Even though I have set up a Github action to check the code style, running npm run lint -- --no-fix only logs the warnings and does not cause the workflow to fail. I r ...

Signing up for event using react leaflet

I've been working on integrating React-Leaflet into my Create React App. I've successfully overlaid GeoJSON data on a base map, but I'm struggling to register clicks on this layer. While troubleshooting this problem, I came across a helpful ...

Angular 2 - Module 'ng-factory' not found

I am encountering an issue when trying to launch my clean UI theme using 'ng serve'. This is my first time working with Angular and I'm struggling to resolve this problem. Any assistance would be greatly appreciated. I have attempted re-inst ...

Having trouble transitioning from Curl to Axios in Node.js? Encountering issues when trying to make a curl request using the provided certificates, resulting in ECONNRESET or

I've been struggling to make a successful curl request in Axios (Node.js) without any luck. A typical working curl request I use (can't provide exact details as the API is private) is like this: curl --cacert server.pem --cert client.pem:123pas ...

Sending a POST request using Node.js Express: A step-by-step guide

Looking for help on sending a post request from node.js Express with data passing and retrieval. Preferably a straightforward method like cURL in PHP. Can anyone assist? ...

What sets apart a plugin from a component in ExtJS?

Can you explain the key distinction between a plugin and a component in extjs? How do you decide whether to implement and use certain behavior as a class or a plugin? ...

Is it possible for me to run npm commands directly within Visual Studio?

Is it possible to run npm commands (such as npm init, npm install) directly from Visual Studio 2017 on an Asp.Net Core 2.0 project? Perhaps through the command line or a context menu option? Currently, I have a context menu command for Bower when right-c ...