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

Attempting to minimize the repetition of code in Redux by implementing some utility functions

Is there a potential issue with the method I'm attempting in this URL: The concept involves altering only the actions file when introducing a new action. One improvement I am considering is recursively merging the status passed from the actions with ...

Identify Pressed Shift Key Direction - Leveraging JQuery

I am currently working on a web application that requires users to enter capital letters. However, I want to restrict them from using the right shift key for certain keys like a, s, d, f and the left shift key for h, j, k, l in order to detect whether they ...

Having trouble retrieving JSON data following file read operation

I've been on a quest to find a way to read JSON files using JavaScript. The tutorial that came the closest to what I needed is located here: https://gist.github.com/zuch/6224600. cells.json: { "cells": [ { "img": "img/singlestitch_thumb. ...

How do I retrieve the download URL for the file created using Python in my Heroku App?

After developing my Flask App, I uploaded several files to the Heroku filesystem. I'm aware that these files are removed every time the dyno restarts. Now, in my HTML/JavaScript frontend, I'd like to provide users with a download button for thes ...

Splitting JavaScript Arrays: Exploring Efficient Division

I'm attempting to develop a recursive function that divides an array in half until it only consists of lengths of 3 and 2. After dividing, I want to neatly organize all the new arrays into another array. My idea is to find a way to determine the numb ...

Fetching a collection from Cloud Firestore using Angular and Firebase

I'm looking to figure out how to retrieve lists from cloud firestore. Here is how I upload a list : export interface Data { name: string; address: string; address2: string; pscode: string; ccode: string; name2: string; } constructor(pri ...

Puppeteer cluster crashes unexpectedly upon invoking cluster.close() following cluster.queue() execution

So here's the deal - I developed an app for web scraping that requires the ability to run multiple processes simultaneously (more than one Chromium instance). To achieve this, I implemented puppeteer-cluster. While I successfully managed to initiate s ...

Updating v-model with inputs is proving to be a difficult task

Creating object instances as responses can be done like this: <el-input :id="'question_' + question.id" v-model="answers[question.id]"></el-input> When entering data into these inputs, the output will look something like this: Answ ...

Creating a progress bar with a mouse listener in React Material Design

I encountered an issue while working with React and React Material-UI components. Here is what I'm trying to achieve: 1) When the user clicks a button in my component, I want to add a mousemove listener to the page and display a ProgressBar. 2) As ...

Trying my hand at using JQuery to dynamically update the image source of a draggable element upon dropping

Essentially, I have an object being dragged with the class .dragme, a dropzone with the class .dropzone1 for it to be dropped at, and an image that I want the .dragme object to become once it has been dropped. My current code looks like this: $(".dropzon ...

graphic map and paintbrush

I've implemented an image map using shape circles, but now I'm looking for a way to draw visible circles or icons on the map. Is there a solution for this issue? Currently, I have used a canvas overlay on the image to draw on it This method wo ...

A plug-in for TinyMCE that allows users to adjust column widths within a table

We utilize TinyMCE in our content management system (CMS), and our users have expressed interest in being able to adjust the width of a column within a table. While HTML technically does not recognize columns, the Moodle editor HTMLAREA includes a plugin t ...

Converting JavaScript functions to Java remote method interfaces

Experience: A while back, I was involved in developing a Java Server-Client application for building automation purposes. Initially, we used Java RMI to connect the server and client but soon realized that utilizing JavaScript for the client side would be ...

Unusual issue with jQuery function failing to detect click events

As I delve into my first jQuery function, the primary goal is to assign a form to the function. Upon clicking the submit button, it should perform validation on each :input field within the function. The form is set as the selector for the function: $("f ...

When clicking on the dress in the masque, how do I change the attire so that it is instantly applied to the masque?

$("#tail").kendoFlatColorPicker({ preview: false, value: "#000", change: select }); $("#head").kendoFlatColorPicker({ preview: false, value: "#e15613", change: select }); I implemented the color ...

Trouble accessing selected value from drop down list in ASP.NET codebehind following modification of Javascript attribute

Does anyone know why ASP.NET code behind cannot retrieve the selected value? After investigating, I discovered that the issue lies within the JavaScript function; Specifically in the set attribute section: process.options[process.selectedIndex].setAttrib ...

An effective method for modifying the active class on an li element in jQuery and ensuring that the user is directed to the desired page upon clicking the li element

I am facing an issue with my script tag. When I click on the links test.php or test2.php, the active class changes from index.php to the respective file but I am not redirected to the clicked page. I have tried solutions from various sources but none of th ...

Mixing unpredictable and inconsequential symbols when revising a JSON document

Apologies for the lack of clarity in my problem description, but I am struggling to identify the exact nature of the issue. So, here it is. I possess a python file named edit-json.py. import os, json def add_rooms(data): if(not os.path.exists('r ...

By default, make the initial element of the list the selected option in an AngularJS select input

I'm running into an issue with setting the first element in my ng-repeat list within a select input. Here is the code snippet causing the problem: <div> <span >OF</span> <select ng-model="eclatementCourante.ordreFabricationId" n ...

What is the process for updating a Markdown widget using the VSTS Rest API?

I am currently exploring the possibilities of using this REST API to make updates to a "Markdown" widget that is located on a dashboard within VSTS. Upon attempting to utilize the JSON body provided in the example, I encountered an issue where I received ...