After a postback in JavaScript, the Root Path variable becomes null

I have been attempting to save the Root URL in a JavaScript variable within my _Layout.cshtml like this:

<script type="text/javascript>
    var rootpath = "";
    $(document).ready(function () {
        rootpath = "@VirtualPathUtility.ToAbsolute("~/")";
    });
</script>

Then in my views:

<script src="~/Scripts/Sales/AddInvoice.js"></script>
    @using(Html.BeginForm("Save","Invoice",FormMethod.Post,new { @id = "frmInvoice" }))
    {
    }

In my JS file, I am using rootpath as follows:

prepUIAutocomp(rootpath + "Sales/Invoice/GetCustomer", "clientid", "ClientMst_clientname", {}, null, 1);

Everything works well until there is a postback or refresh, after which rootpath becomes undefined.

Since each view utilizes _Layout.cshtml, shouldn't the path be updated with each request? Or am I overlooking something?

I would like to utilize the rootpath variable in all my views and their associated JavaScript files for generating AJAX URLs. Any recommendations?

Thank you.

Answer â„–1

Seems like it's been a slow day today. I had to make some adjustments to my script, and luckily it worked. Sharing it here in case anyone else is experiencing a similar issue.

<script type="text/javascript>
    var rootpath = "";
    $(document).ready(function () {
        var x = "@VirtualPathUtility.ToAbsolute("~/")";
        if (x && x != "")
            rootpath = x;
    });
</script>

However, I still have the same initial question.

Why might the value of

VirtualPathUtility.ToAbsolute("~/")
be null initially?

And what could be causing the disappearance of the rootpath value?

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 code is functioning properly, however it is returning the following error: Anticipated either

Can you explain why this code is resulting in an unused expression error? <input style={{margin:'25px 50px 0',textAlign:'center'}} type='text' placeholder='add ToDo' onKeyPress={e =>{(e.key ==='En ...

Executing an Ajax callback function to navigate to a different page

I must handle ajax errors globally by capturing 901 error codes in my header.jsp. There is an error message displayed in the browser console: GET https://localhost:8443/SSApp/Pan/report?&vessel…namax%20Tanker%20Pool%20Limited&rptTitle=Activit ...

Generate a loop specifically designed to execute the code following the menu in the script

My website has the code snippet below: let txt_com = document.querySelector(".text_user"); let num_com_user = document.querySelector(".massage_for_user"); txt_com.addEventListener("click", function() { if (this.classList.contains("num_com_user")) { ...

Use PipeTransform to apply multiple filters simultaneously

Is it possible to apply multiple filters with PipeTransform? I attempted the following: posts; postss; transform(items: any[]): any[] { if (items && items.length) this.posts = items.filter(it => it.library = it.library ...

Single-select components in React Native

I am currently working on implementing a simple single selectable item feature, illustrated in the image provided below. https://i.stack.imgur.com/U2rJd.png At this moment, I have set up an array containing my data items and utilized the .map function to ...

Can you please highlight parts of the text and provide dialogue with additional information?

I am currently enhancing my blog and looking for a way to implement JavaScript functionality that will help highlight specific parts of my text and provide additional information, like: I am currently working on my laptop When the user clicks on "lapto ...

What could be the reason for the lack of read or write functionality in $cookies for angular version 1.6.6?

I am relatively new to working with Angular. I have started a test project and my goal is to store user authentication in cookies. Despite my best efforts, I keep encountering an undefined error when attempting to retrieve the stored value. I am not sure w ...

What is the procedure for iterating through the square brackets of a JSON array?

Here's the data I have: $json_data_array = '[ { "id": 1, "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd7cdffcbdacccb91dcd0d2">[email protected]</a>", ...

End the child process.execution after a specific amount of time

I have been searching for information on child process waiting time or response waiting time, but I haven't found anything useful. I'm in need of something like that, so I hope someone can assist me. When I look at the code below, I am printing ...

Various redirects based on multiple referrers

Here is the code I have for redirecting based on the referer: document.addEventListener('DOMContentLoaded', function() { console.log(isMobile); var referrer = document.referrer; if(referrer.indexOf('site1.com') !== -1 || referrer ...

How can the dot badge in Material-UI be enlarged?

I'm in need of a badge component that serves as an indicator without displaying any values. I opted for the dot variant, but it's too small for my liking. I tried modifying it with CSS, but it doesn't seem to be working as expected. Any sugg ...

Navigate through the elements of an Ext.form.CheckboxGroup using Ext JS

Currently, I am working with an Ext.form.CheckboxGroup that contains multiple items of Ext.form.Checkbox. I am wondering if there is a way to iterate through each item within the Ext.form.CheckboxGroup? I attempted the code below without success: for ( ...

Retrieving CSS style values with Node.js

I am looking to design a new CSS style that includes the lowest and highest values. table[my-type="myStyle"] { width: 255.388px !important; } This code snippet is included in numerous CSS files within my style directory. ...

Using Ajax and PHP to Trigger a Forced Download

I am trying to develop a download script that enables the Force Download of JPGs. Below is my PHP script: <?php header("Pragma: public"); // required header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); ...

Learn how to use Javascript and ASP.NET to refresh the parent page in Mozilla Firefox browser

The code window.opener.location.reload(); works well in Internet Explorer, but it doesn't refresh the parent page in Mozilla Firefox. Can someone please advise me on how to refresh the parent page in a way that is cross-browser compatible? Here is th ...

Exploring the process of breaking down a substantial string object into manageable key/value pairs using AngularJS

I gathered information from a text file called sample_resume.txt Name: John Doe Phone: (555) 555-5555 Email: [email protected] TARGET To succeed in the field of web development. SKILL SET Development: HTML5, JavaScript, Bootstrap, AngularJS, Rea ...

Is there a compatibility issue between Vue particles and my project?

Greetings to all! I recently added Vue Particle to my Vue project, but encountered an issue while importing VueParticles in the Main.js file. Here is a snapshot from my terminal for reference. https://i.stack.imgur.com/Bxh2r.png ...

Stable Banner with Automatic Scroll to Sections

I have implemented a script that allows for smooth scrolling to different sections within a webpage when clicking on links in the top navigation menu. In the HTML, I've assigned IDs to each section (section1, section2, section3, etc.) and linked these ...

The JavaScript file fails to load when accessing port 8080

As I embark on my journey into backend development, please bear with me. Currently, I am working on a JavaScript program that retrieves text data from my localhost. I have set up an HTTP server using Node.js which serves as a regular HTTP server. The serve ...

On the server side, the received Req.body appears as an empty object: { }

import { Injectable } from '@angular/core'; import { Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; impo ...