None of the Views are rendered after executing RedirectToAction

I created a Login Page that redirects to the required page after validation. However, when it redirects, the previous Login page view appears instead of the expected view.

Below is the JavaScript code I am using:

    function abc() {
        var email = document.forms["MyForm"]["Email"].value;
        var password = document.forms["MyForm"]["Password"].value;
        if (email.length == 0 || password.length == 0) {
            alert("Email and Password Field Required");
            return false;
        }
        else {


            $.ajax({
                 url: $("#MyForm").attr('action'),
                type: $("#MyForm").attr('method'),
                data: $("#MyForm").serialize(),
                success: function (data) {
                     alert("Invalid Email or Password");
                }
            });
        }
    }
</script>

And here is the controller [HttpPost]:

    public ActionResult UserLogin(Models.UserModel selectedDocuments)

    {                                  
        if (ModelState.IsValid)
        {
            long AdminID = IsValid(selectedDocuments.Email, selectedDocuments.Password);
            if (AdminID != 0)
            {
                FormsAuthentication.SetAuthCookie(selectedDocuments.Email, false);
                if (RoleID == 1)
                {
                    Session["SystemAdmin"] = true;
                    Session["AdminID"] = AdminID;
                    return RedirectToAction("ClubInfo", "Admin");
                }
                // Additional role checks and redirects...
              
            }
            else
            {
                ModelState.AddModelError("", "Login Data Is Incorrect.");

            }
        }
        return Json(new { selectedDocuments = "Whatever you want to send" }, JsonRequestBehavior.AllowGet);
    }

I need help in successfully implementing this. Can somebody please assist me?

Answer №1

When a form is submitted using an ajax call, the view will be returned as a response to the ajax call, preventing the user from seeing the redirected view directly.

Instead of using return RedirectToAction(), you can use return Json and redirect from the client side:

return Json(new 
               { 
                RedirectUrl= Url.Action("ClubInfo", "Admin")
               }
               ,JsonRequestBehavior.AllowGet);

In the success function of the ajax call:

success: function (data) {
                     window.location.href = data.RedirectUrl;
                }

Answer №2

One way I achieve this is by modifying the redirect mechanism.

To accomplish this in code:

return Json(Url.Action("ClubInfo", "Admin"));

And then, in JavaScript:


$.ajax({
    url: $("#MyForm").attr('action'),
    type: $("#MyForm").attr('method'),
    data: $("#MyForm").serialize(),
    success: function(result) {
        window.location.href = result;
    },
    error: function() {
        alert("Invalid Email or password");
    }
});

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

Using Javascript to save a numeric value and accessing it on a different webpage

I'm encountering an issue with a specific feature on my website. I want users to click on a hyperlink that will redirect them to an application form page. The challenge is ensuring that the reference number (a 5-digit code displayed as a header) is st ...

The consistency of values remains constant throughout all Ajax requests

I am presenting the code snippet below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" ...

What causes the Invariant Violation: Invariant Violation: Maximum update depth exceeded error to occur when using setState()?

Looking for some help with this component: // here are the necessary imports export default class TabViewExample extends Component { state = { index: 0, routes: [ { key: 'first', title: 'Drop-Off', selected: true }, ...

Tips for passing multiple values with the same key in Axios as parameters

I need to develop a function that allows users to select multiple categories and subcategories, then send their corresponding ids as a query string using Axios. For example, if a user selects category IDs 1 and 2, along with subcategory IDs 31 and 65, the ...

React Native: How come my text is breaking like this and failing to adhere to the container's margin settings?

I am facing a challenge in React Native where I need to display multiple elements next to each other, with a flex wrap when there are too many elements or if the text is too long. Each element consists of an icon and text, with the text breaking into the n ...

Guide on dynamically updating a div in PHP with a mix of text output and images at regular intervals

My current project involves creating a browser-based card game primarily using PHP, with potentially incorporating other languages to help me enhance and test my PHP skills. However, I've encountered difficulties while attempting to implement various ...

Identifying activity on a handheld device

I am currently working on a website and I have noticed that it doesn't work as well on mobile devices as it does on desktop. There are performance issues that need to be addressed. I've seen other websites redirecting users to a different page wh ...

Creating an MP3 Text to Speech file with IBM Watson

I have been referring to the documentation for implementing the IBM Watson Text-to-Speech API using Node.JS. My goal is to generate output files in MP3 format. The documentation suggests modifying the base code, but I'm struggling with this. The resu ...

Sending data from TextBoxFor to controller with @Ajax.ActionLink in MVC

I’ve gone through numerous questions dealing with the same issue, yet none of them seem to solve my problem (or I’m completely missing the point). As the title suggests, I am attempting to transfer the value from a TextBoxFor to my controller using an ...

Deploy Node.js on a Debian server hosted on Google Compute Engine

Currently, I am operating a Debian server on Google Compute Engine using a host called example.com. My goal is to run a node.js app within a specific directory on this server, for instance, example.com/mynodeapp. Fortunately, the necessary components such ...

Creating an iPad-inspired password field experience in a text input with jquery: A step-by-step guide

Looking for a plugin that mimics the iPad's password field behavior for credit card number entry. The focus should only reveal the entered digit and then switch to a bullet as the next digit is typed. Additionally, all previously entered digits should ...

JQuery fixed div bounces unpredictably when scrolling

Currently, I have a scenario on my webpage where there is a div called RightSide positioned on the far right side below another div named TopBanner. The TopBanner div remains fixed at the top of the screen even when the user scrolls down, which is exactly ...

Removing an event from Fullcalendar

With the help of a post on StackOverflow, I managed to modify my select: method to prevent users from adding an event on a date before NOW. However, there is a drawback. When a user clicks on an empty time slot and the system displays an alert message, th ...

Tips on creating a button that, upon clicking, triggers the download of an Excel file using PHPSpreadsheet

I am trying to figure out how to create a button that, when clicked, will download an Excel file named b1b5.xls with some specified values added. Here is the code I have so far: <html> <head> </head> <body> <center> < ...

Why is the lifecycle callback not being triggered?

I am currently learning how to develop with Vue.js. I have been trying to use the lifecycle callbacks in my code. In my App.vue file, I have implemented the onMounted callback. However, when I run the code, I do not see the message appearing in the consol ...

Steps to automatically populate the dropdown upon page load

Hello, I have a question regarding setting a value to a dropdown list in JavaScript. Currently, I am trying to execute this function during the onload event of the body tag. However, I am facing issues with setting the value. Below is the code: function s ...

In what format is the parameter accepted by the .getDay() method?

Here's the plan: I need to extract information from an input element with type set as date. This data will then be stored in a .json file and later parsed when the program is initiated. Subsequently, I aim to utilize the date.getDay() function to dete ...

Transmit a basic JSON object from a Node.js server to an index.html webpage

People often overlook this seemingly simple solution when I search for it on Google. My goal is to send a basic json message or file to my index.html page. Here's the Node.js code: const express = require('express'); const app = express(); ...

Transferring JSON data with a cURL POST request to Sinatra

I have developed a basic API using Sinatra to send emails based on JSON data submitted. While I can successfully submit the data via a form and access the necessary parameters like 'to', 'subject', and 'body', I am facing diff ...

Leverage the OpenWeather Icons to Pinpoint Locations on a Leaflet Map

Having some trouble incorporating weather icons from an openweather API call as markers on my leaflet map. The icons should appear in a popup on the marker within an img tag. However, despite confirming the correct icon URL through console.log, they only ...