'Redirect to Action not working using MVC asp.net

I have a requirement, where I validate user using Windows Authentication. Till there it works perfectly fine. But when I try to redirect to respective controllers it does nothing.

Below is my code:

public ActionResult ValidateUser(string strUsername, string strPassword)
    {
        string strReturn = "";
        string strDbError = string.Empty;
        strUsername = strUsername.Trim();
        strPassword = strPassword.Trim();

        UserProviderClient ObjUMS = new UserProviderClient();            
        bool result = ObjUMS.AuthenticateUser(strUsername, strPassword, out strDbError);

        Session["isUserAuthenticated"] = result;

        if (result == true)
        {
            Session["isUserOutsideINDomain"] = true;
            Session["OutsideINDomainUsername"] = strUsername;
            //redirect to respective controller

            UMS ObjUMSDATA = new UMS();

            string strUserName = "";
            string strCurrentGroupName = "";
            int intCurrentGroupID = 0;

            strUserName = System.Web.HttpContext.Current.User.Identity.Name.Split('\\')[1];                
            _UMSUserName = strUserName;

            if (!string.IsNullOrEmpty(strUserName))
            {
                List<UMSGroupDetails> lstUMSGroupDetails = null;
                List<UMSLocationDetails> lstUMSLocationDetails = null;

                ObjUMSDATA.GetUMSGroups(strUserName, out strCurrentGroupName, out intCurrentGroupID, out lstUMSLocationDetails, out lstUMSGroupDetails);
                if (strCurrentGroupName != "" && intCurrentGroupID != 0)
                {
                    ViewBag.LoginUserName = strUserName.ToUpper();
                    ViewBag.CurrentGroupName = strCurrentGroupName;
                    ViewBag.CurrentGroupID = intCurrentGroupID;
                    ViewBag.GroupDetails = lstUMSGroupDetails;
                    ViewBag.LocationDetails = lstUMSLocationDetails;
                    TempData["Location"] = lstUMSLocationDetails;

                    TempData["strCurrentGroupName"] = strCurrentGroupName;
                    TempData.Keep();

                    if (strCurrentGroupName == "NEIQC_SAP_ENGINEER")
                    {
                        return RedirectToAction("Assign","App"); // here its not redirecting properly.
                    }
                    else if (strCurrentGroupName == "NEIQC_FIBER_ENGINEER")
                    {
                        return RedirectToAction("App", "Certify");
                    }
                    else if (strCurrentGroupName == "NEIQC_CMM")
                    {
                        return RedirectToAction("App", "Approver");
                    }
                }
                else
                {
                    return RedirectToAction("ErrorPage", "UnAuthorize");
                }
            }

        }
        else
        {
            strReturn = "Login UnSuccessful";
        }

        return Json(strReturn);
    }

Why is it not working?

Update

My route config details.

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
            
        );
        routes.MapRoute(
            name: "Assign",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "App", action = "Assign", id = UrlParameter.Optional }               
        );
       
    }

Ajax call

function validateUser() {
    var getUserName = $('#txtUsername').val();
    var getPassword = $('#txtPassword').val();

   // console.log(getUserName);
    //console.log(getPassword);

    var Values = { "strUsername": getUserName, "strPassword": getPassword };

    $.ajax({
        url: AppConfig.PrefixURL + "Home/ValidateUser",
        dataType: 'json',
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify(Values),
        processData: false,
        success: function () {
        },
        error: function () {
            
        }
    });
}


Solution 1:[1]

Your route config cannot differentiate between two routes that you have given because they are not different. Also, your default route should always be at the end. Kindly change route config to this:

Notice, I changed the url for your "Assign" route and moved "Default" route at the end.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Assign",
        url: "App/{action}/{id}",
        defaults: new { controller = "App", action = "Assign", id = UrlParameter.Optional }               
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }

    );

}

Solution 2:[2]

Since you're calling the controller action using AJAX, obviously RedirectToAction won't work there because AJAX call intended to stay in the same page. You should return JSON string for all responses and use switch...case block or if-condition on client-side script to redirect into corresponding actions, with location.href and @Url.Action() helper to generate URL string:

[HttpPost]
public ActionResult ValidateUser(string strUsername, string strPassword)
{
    string strReturn = "";
    string strDbError = string.Empty;
    strUsername = strUsername.Trim();
    strPassword = strPassword.Trim();

    UserProviderClient ObjUMS = new UserProviderClient();            
    bool result = ObjUMS.AuthenticateUser(strUsername, strPassword, out strDbError);

    Session["isUserAuthenticated"] = result;

    if (result == true)
    {
        Session["isUserOutsideINDomain"] = true;
        Session["OutsideINDomainUsername"] = strUsername;
        //redirect to respective controller

        UMS ObjUMSDATA = new UMS();

        string strUserName = "";
        string strCurrentGroupName = "";
        int intCurrentGroupID = 0;

        strUserName = System.Web.HttpContext.Current.User.Identity.Name.Split('\\')[1];                
        _UMSUserName = strUserName;

        if (!string.IsNullOrEmpty(strUserName))
        {
            List<UMSGroupDetails> lstUMSGroupDetails = null;
            List<UMSLocationDetails> lstUMSLocationDetails = null;

            ObjUMSDATA.GetUMSGroups(strUserName, out strCurrentGroupName, out intCurrentGroupID, out lstUMSLocationDetails, out lstUMSGroupDetails);
            if (strCurrentGroupName != "" && intCurrentGroupID != 0)
            {
                ViewBag.LoginUserName = strUserName.ToUpper();
                ViewBag.CurrentGroupName = strCurrentGroupName;
                ViewBag.CurrentGroupID = intCurrentGroupID;
                ViewBag.GroupDetails = lstUMSGroupDetails;
                ViewBag.LocationDetails = lstUMSLocationDetails;
                TempData["Location"] = lstUMSLocationDetails;

                TempData["strCurrentGroupName"] = strCurrentGroupName;
                TempData.Keep();

                // here you need to return string for success result
                return Json(strCurrentGroupName);
            }
            else
            {
                return Json("Error");
            }
        }

    }
    else
    {
        strReturn = "Login UnSuccessful";
    }

    return Json(strReturn);
}

AJAX call

$.ajax({
    url: AppConfig.PrefixURL + "Home/ValidateUser",
    dataType: 'json',
    type: 'post',
    contentType: 'application/json',
    data: JSON.stringify(Values),
    processData: false,
    success: function (result) {
        switch (result) {
            case 'NEIQC_SAP_ENGINEER':
               location.href = '@Url.Action("Assign", "App")';
               break;
            case 'NEIQC_FIBER_ENGINEER':
               location.href = '@Url.Action("Certify", "App")';
               break;
            case 'NEIQC_CMM':
               location.href = '@Url.Action("Approver", "App")';
               break;
            case 'Error':
               location.href = '@Url.Action("ErrorPage", "UnAuthorize")';
               break;
            case 'Login UnSuccessful':
               // do something
               break;

            // other case options here

        }
    },
    error: function (xhr, status, err) {
        // error handling
    }
});

Additional note:

The RouteConfig process routes from most-specific to more-general routes, hence Default route must be declared in last place, and custom route definition must be different from default one.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Assign",
        url: "App/{action}/{id}",
        defaults: new { controller = "App", action = "Assign", id = UrlParameter.Optional }               
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
    );

}

Solution 3:[3]

So you have a current ajax call such as this:

$.ajax({
    url: AppConfig.PrefixURL + "Home/ValidateUser",
    dataType: 'json',
    type: 'post',
    contentType: 'application/json',
    data: JSON.stringify(Values),
    processData: false,
    success: function () {
    },
    error: function () {

    }
});

This is fine however the success does nothing at the moment. You have a controller method that returns the string

return Json(strReturn);

Now I want you to instead of returning that, return the role instead as a string.

I want your ajax to resemble this:

$.ajax({
    url: AppConfig.PrefixURL + "Home/ValidateUser",
    dataType: 'json',
    type: 'post',
    contentType: 'application/json',
    data: JSON.stringify(Values),
    processData: false,
    success: function (result) {
        //Here we will be returning the role as a string from the first ajax call and using it to check against in here

        //I just want you to essentiatly do the if statements in the controller here such as this

        if(result == "NEIQC_SAP_ENGINEER")
        {
            window.location.href = '@url.Action("Assign", "App")'
        }
    },
    error: function () {

    }
});

EDIT: This answer seems to be very similar to @TetsuyaYamamoto 's. Both should work however the preference of whether or not to use a switch statement is completely up to you

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Priyank Panchal
Solution 2 Tetsuya Yamamoto
Solution 3 JamesS