简体   繁体   中英

How to redirect one action to another action in MVC5?

I want to RedirectToAction to another action inside of a method. I used:

return RedirectToAction("ActionName", "ControllerName");

But I am getting an error, it doesn't hit the other action.

My Controller Code:

public ActionResult VisitCount(VisitorsViewModel objvvm)
{
    var UserID = System.Web.HttpContext.Current.Session["UserID"].ToString();
    var objEmpDepUTID = db.UserRightsSettings
        .Where(u => u.UserID.ToString() == UserID)
        .Select(e => new
        {
            objemployeeID = e.EmployeeID,
            objdepartmentID = e.DepartmentID,
            objusertypeID = e.UserTypeID
        })
        .FirstOrDefault();

    var EmployeeID = objEmpDepUTID.objemployeeID;
    var DepartmentID = objEmpDepUTID.objdepartmentID;
    var UserTypeID = objEmpDepUTID.objusertypeID;

    if (DepartmentID == new Guid("47D2C992-1CB6-44AA-91CA-6AA3C338447E") &&
       (UserTypeID == new Guid("106D02CC-7DC2-42BF-AC6F-D683ADDC1824") ||
       (UserTypeID == new Guid("B3728982-0016-4562-BF73-E9B8B99BD501"))))
    {
        return RedirectToAction("Index1", "NextFollowUp");
    }
    else
    {
        return RedirectToAction("Index2", "NextFollowUp");
    }
}

private ActionResult Index1()
{
    return View();
}

private ActionResult Index2()
{
    return View();
}

The above code is not working correctly - it doesn't hit the other action when the if condition satisfies. I tried all methods but I didn't find any solution.

If you're inside the same controller, try this:

return RedirectToAction("Index1");

Instead of:

return RedirectToAction("Index1", "NextFollowUp");

If you're calling the action from another controller, use this:

RedirectToAction("Index1", "NextFollowUp");  

Or try this code:

return View("ActionName");

Like this:

if (DepartmentID == new Guid("47D2C992-1CB6-44AA-91CA-6AA3C338447E") &&
   (UserTypeID == new Guid("106D02CC-7DC2-42BF-AC6F-D683ADDC1824") ||
   (UserTypeID == new Guid("B3728982-0016-4562-BF73-E9B8B99BD501"))))
{
   return View("Index1");
}
else
{
    return View("Index2");
}

You cannot redirect to a method marked private . Your need to make your methods public .

public ActionResult Index1()
{
    return View();
}
public ActionResult Index2()
{
    return View();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM