What is the best method for assigning a ViewData value to a JavaScript variable?

Currently, I am facing an issue where I need to transfer a ViewData from the Controller in the back-end to a JavaScript variable in the front-end. The ultimate goal is to incorporate this variable into an API call through AJAX.

This is what I have been able to put together:

  1. Controller
public ActionResult Index()
            {
                ViewData["xTokenBackEnd"] = "IAMATOKEN";
                return View();
            }
  1. Index.cshtml
    var xTokenFrontEnd = @Html.Raw(Json.Encode(ViewData["xTokenBackEnd"]));
    $.ajax({
                    type: 'GET',
                    url: 'https:&token=' + xTokenFrontEnd,
                    dataType: 'json'
                }).done(function (result) {})

Upon execution of the application, the token value appears correctly at the end of the URL like this: https:&token=IAMATOKEN. However, despite this, no data seems to be received through the AJAX call. It seems that while the token value is present in the URL, it may not hold any real significance. Could there be a need for further conversion? Interestingly, if I manually input "IAMTOKEN" instead of using the xTokenFrontEnd variable, everything works perfectly fine. This leads me to believe that the issue might lie in how I am appending xTokenFrontEnd to the URL. Any suggestions on resolving this predicament?

Answer №1

To capture a value in your view and store it in a variable, you can follow this example:

string authToken = ViewData["authToken"];

Next, create a hidden field with this variable like so:

@Html.Hidden("hiddenAuthToken", @authToken)

You can then retrieve this value using jQuery:

var token = $('#hiddenAuthToken').val();

Finally, you can utilize this value in an ajax call.

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

Error message stating that there is no property 'collection' in Firestore when using Firebase v9 modular syntax in Firebase Firestore

Working on a React application that makes use of Firebase Firestore for handling database operations, I recently upgraded to Firebase version 9 and adopted the modular syntax for importing Firebase services. Nevertheless, when attempting to utilize the co ...

Enforce linting rules for webpack aliases using ESLint

I am currently working with a webpack configuration file that functions as a factory (react-universally boilerplate). In this setup, I have included an resolve option structured like so: resolve: { // These extensions are attempted when resolving a ...

How can you leverage the power of useState in a custom React hook?

Here is a code snippet for a custom hook I created: const useShowBg = () => { const [showBg, useShowBg] = useState(false); return [showBg, useShowBg]; }; export default useShowBg; In my component, I import and use the custom hook like this: im ...

Retrieve the contents within a div that has a CSS property of position:absolute using

<table id="droppable" border="1" style="position: relative"> <tr> <td>a1</td> <td>b1</td> <td>c1</td> <td>d1</td> <td>e1</td> <td>f1</ ...

What is the process for transforming an entire page into a docx file?

I am currently working on a project where I need to create a downloadable form. I am utilizing ReactJS to render an HTML page, and now I am looking for a solution to convert this page into a .docx file. Do you have any suggestions or ideas on how to achi ...

Prevent automatic form filling in ASP.NET C# by disabling browser autocomplete for textboxes

Is there a way to prevent browsers from autocompleting textboxes in an ASP.NET C# application? I've attempted using the following jQuery code, but it doesn't seem to be working: $(document).ready(function () { $("input[type=text]").attr("aut ...

Execute the PHP POST request to query "SELECT * FROM .... WHERE ..."

Trying to send a user's ID from my Android app to retrieve their information from the SQLite database on the server using the $_POST method request. Following tutorials, I learned that mysqli_query() will return an Object for a successful SELECT query ...

Encountering complications while attempting to integrate Ng-SweetAlert-2 into AngularJS

Concerning this particular project After following the installation process outlined in the description, I encountered an error: Error: [$injector:unpr] Unknown provider: 19degrees.ngSweetAlert2Provider <- 19degrees.ngSweetAlert2 <- prkctrl` I hav ...

What could be causing Express.js to return two responses from the server?

As a beginner in learning express.js and node.js, I am currently working on creating a basic server using the following code: const http = require('http'); const express = require('express'); const app = express(); ap ...

The placeholder text is not displaying with bullets in Internet Explorer. However, it is functioning correctly in Chrome

I need assistance displaying the placeholder text in IE8 as shown below: "Any relevant reference numbers, such as Direct Debits: - Name of the Branch (if applicable) - What was the original problem - Date the problem occurred " While it appears correct ...

Mastering Dropdown Navigation and Value Setting in Angular

I am facing a challenge with two components named ComponentA and ComponentB. In ComponentB, there is a link that, when clicked, should navigate to ComponentA and send specific data to it. This data needs to be displayed in the dropdown options of Component ...

When exporting data from Datatable to Excel, decimal values including the % symbol may experience rounding issues

I am facing an issue when trying to export a Datatable to an excel sheet. The column in the Datatable contains decimal values with a % symbol. However, after exporting, the decimal values are being rounded off. I need the decimal values along with the % sy ...

Using Selenium webdriver to assign a JSON object to a paragraph element

What is the correct way to insert a JSON object into a p tag inside an iframe? I attempted the following approach but it displayed the text "[object Object]" rather than the actual content of the object... This is my implemented code: var arrJSON = [ ...

HTML5 Audio using AudioJS may not function reliably when loaded remotely

I have been encountering frustrating issues with loading audio tags for a while now. Despite spending nearly two weeks trying to solve the problems, every fix seems to create another one. My webpage includes an < audio > tag that utilizes audio.js t ...

issue encountered while passing a callback in a res.render() function

Currently, I am working on a small application where I am fetching data from remote JSON files to generate statistics that will be displayed in an EJS file later. My objective is to pass separate values for rendering and then utilize them within the EJS d ...

Ember.js Helper that mimics an Ajax request response

After extensive exploration and experimentation, it seems that returning a value from an ajax request in Emberjs is quite challenging. (I could be mistaken.) The issue appears to be related to the asynchronous nature of callbacks. Here lies my predicament ...

Utilize Node.js and Socket.IO to download a PNG image in a web browser

Looking for assistance in saving an image from Flash to a server using node.js. Below is my code snippet: var pngEncoder:PNGEncoder = new PNGEncoder(); var pngStream:ByteArray = PNGEncoder.encode(bmd); socket.send(pngStream,"image"); Above is the Flash c ...

What is the best way to pass a JavaScript variable to an Ajax script?

Within an html button, I have the following onclick event: onclick='javascript:updateStatus(59)' This event calls the function below: function updateStatus(){ $.ajax({ type: 'post', url: '/update-status.php', ...

The state remains unchanged when clicking on the div element

I am encountering an issue when trying to change the data attribute data-sort of a clicked DIV. Despite my efforts, I can only seem to get the value "DESC" each time. How can I successfully modify the data-sort attribute based on user interaction? jQuer ...

Enhancing user input with multiple values in a textarea using JSTL

I'm having trouble inputting multiple values into a textarea using JSTL. Here is the coding snippet I am using: <label>Resources</label> : <c:forEach items="${MEETING_ENTITY}" var="resource"> <textarea id ...