Retrieve the session variables in a controller while making an ajax request

In my controller, I am populating certain fields with data.

 public string AjaxLogin()
        { 
          //some code to check admin or not
           Session["UserName"] = "Smith";
           if(type="Admin")
           {
              Session["UserRole"] = 1;
           }
           Session["EmployeeID"] = 101;
        }

I have made an ajax request to this controller as shown below, and upon success, I need to access the session variables within the success function in order to verify the user's role.

      $.ajax(
             {
                url: GLOBAL.GetAppPath() + 'Home/AjaxLogin',
                data: data,
                type: 'POST',

                error: function (xhr, status, error) {
                     console.log(error);
                },

                success: function (result, status, xhr) {
                      if (result == 'OK') 
                      {                          
                        var UserVal = '@Session["UserRole"]';
                        alert(UserVal);
                        if(UserVal == 1)
                        {
                         var baseUrl ="@Url.Action("Admin","AdminPage")";
                        window.location.href = baseUrl;                           
                        }
                        else
                        {
                           var baseUrl ="@Url.Action("Admin","RegularPage")";
                           window.location.href = baseUrl;
                        }
                      }
                     else {
                             $('#msgError').html('Error: ' + result);
                             $('#msgError').css('display', 'block');
                          }
                      },
                  });

However, I am unable to retrieve this variable within this call. I aim to validate the user role variable and redirect to appropriate URL actions based on its value.

Answer №1

If you need to forward to a specific controller within your project, the Url helper can assist you in achieving this. Here is an example:

return JavaScript( "window.location = '" + Url.Action("Edit","Dispatch") + "'" );

Just wanted to mention that I couldn't comment due to the requirement of 50 reputation points.

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

Unable to retrieve information from PHP file using jQuery AJAX

Trying to retrieve data from a PHP file sent via the jQuery AJAX method results in an Undefined Index error. sender.php $('#slot1').click(function(){ var selectedDate = $('#selectedDate').html(); var timeSlot = ...

Is it possible to use a Jasmine spy on a fresh instance?

In need of assistance with testing a TypeScript method (eventually testing the actual JavaScript) that I'm having trouble with. The method is quite straightforward: private static myMethod(foo: IFoo): void { let anInterestingThing = new Interesti ...

Can you identify the programming language used in this code snippet? - {"html":"<section class="page">

I've been approached to assist with a friend's company website since the original developer seems to have disappeared. Apologies if this question is too basic for this forum, and please forgive me if I am not in the right place to ask it. The m ...

"Trouble arises when a single quote is passed from the controller to the client-side MVC

In the Controller method, Serverside code is stored in ViewData with values like 'Double-Click to edit', '7C486', '7C489', '7C490', '7C491', and '7C492'. To display these values in a Dropdown wit ...

Are you utilizing the User Extensions/Plug in feature with ExtJS 4?

In the process of developing a web application, I have decided to include a password strength meter feature. While there are numerous examples available, such as this one, I am encountering difficulties implementing the solution using Sencha Architect. My ...

Transform a collection of objects into an array

In my data array, I have various groups and types: const data = [ { groupName: 'groupName1', types: [ { name: 'name1', displayName: 'displayName1' }, { name: 'name2&apos ...

TypeScript interface with an optional parameter that is treated as a required parameter

Within my interface, I have a property that can be optional. In the constructor, I set default values for this property, which are then overridden by values passed in as the first parameter. If no properties are set, the defaults are used. I am looking fo ...

What is the best way to convert a repetitive string into a reusable function?

I am currently retrieving data from an API and I want to display it on my website in a more user-friendly manner. The challenge I'm facing is that the number of variables I need is constantly changing, along with their corresponding values. So, I&apos ...

¿What is preventing me from merging two arrays within this query handler?

I'm facing an issue while trying to merge arrays from a request with existing arrays in a MongoDB database. Despite my attempts, the arrays do not seem to be merging as expected. Can anyone help me identify what might be causing this problem? router.p ...

Discovering instructions on locating Material UI component documentation

I'm having trouble locating proper documentation for MUI components. Whenever I attempt to replicate an example from the site, I struggle to customize it to fit my requirements. There are numerous props used in these examples that I can't seem to ...

Working with JavaScript Arrays within a JSON file data

I am currently learning React and attempting to display random images from the Picsum website using their API. The JSON file I receive contains various information, but I am specifically interested in extracting the image URLs. Although it appears that my ...

Clicking on a button in the Shield UI Grid Toolbar will apply filters to

Currently, I am working with a grid that utilizes a template for the toolbar. In this grid, there is a column labeled "Status." My goal is to filter the rows so that only those where the Status equals Request to Reschedule, Cancelled, Office Call Required, ...

Transform an SVG string into an image source

Is there a way to convert an incoming string ' ' into an img src attribute and then pass it as a prop to a child component? I attempted the following method, but it hasn't been successful. `let blob = new Blob([data.payload], {type: &apos ...

Loading Jquery autocomplete on page load

I have implemented the jquery autocomplete plugin and it is functioning correctly. However, I am looking to automatically trigger the select function if there is only one item in the dropdown list, so that fields are populated without any user interaction. ...

Disabling the child element from triggering the parent element's onclick function, while still allowing it to respond to its own content

My list elements have onclick-functions that change the display of each element and its child div, moving them to the top of the list. Clicking again reverses this effect. The issue arises because the child div contains search fields, clickable pictures, ...

Guide on making an SVG tooltip using the Menucool JS extension

I am trying to add a simple tooltip to an SVG "map" when the mouse hovers over a rectangle. To create the tooltip, I would like to utilize this specific plugin. Here is how I have connected the SVG to HTML: <object data="map.svg" type="image/svg+xml" ...

Issue occurs when using Angular Firebase $createUser method

I'm stuck on this issue. I'm attempting to set up a user with AngularFire using $firebaseAuth instead of the deprecated FirebaseSimpleLogin, as advised in the documentation. I am confident that the form is submitting a valid email and password, b ...

Displaying two different dates in AngularJS without any repetition of the similar elements

How can I elegantly display a date range that includes two dates, without repeating information if it's the same for both dates? My idea is something like this: Tue, 05 May 2015 19:31-20:31 GMT Mon, 04 19:31 - Tue, 05 20:31 May 2015 It's accept ...

Can the process of rounding values enhance the speed of JSON communication during AJAX requests?

Considering how frequently I need to retrieve large amounts of data multiple times within seconds using the $ajax or jQuery.getJSON method, I am contemplating the idea of rounding long floating-point values (e.g. 1.23242342344...) to shorter versions. My ...

Leverage the power of axios in your React application to retrieve information from an

I have been exploring how to use axios for fetching data from an API (https://reqres.in/) and displaying it in my React application. Previously, I used the fetch method in JavaScript to retrieve data from APIs. Despite trying various resources, I am unsure ...