How to redirect to Index from another controller?

后端 未结 7 1565
滥情空心
滥情空心 2020-12-02 11:06

I have been looking through trying to find some way to redirect to an Index view from another controller.

public ActionResult Index()
{                  


        
相关标签:
7条回答
  • 2020-12-02 11:22

    You can use the following code:

    return RedirectToAction("Index", "Home");
    

    See RedirectToAction

    0 讨论(0)
  • 2020-12-02 11:28

    You can use the overloads method RedirectToAction(string actionName, string controllerName);

    Example:

    RedirectToAction(nameof(HomeController.Index), "Home");
    
    0 讨论(0)
  • 2020-12-02 11:28

    Tag helpers:

    <a asp-controller="OtherController" asp-action="Index" class="btn btn-primary"> Back to Other Controller View </a>
    

    In the controller.cs have a method:

    public async Task<IActionResult> Index()
    {
        ViewBag.Title = "Titles";
        return View(await Your_Model or Service method);
    }
    
    0 讨论(0)
  • 2020-12-02 11:35

    Use the overloads that take the controller name too...

    return RedirectToAction("Index", "MyController");
    

    and

    @Html.ActionLink("Link Name","Index", "MyController", null, null)
    
    0 讨论(0)
  • 2020-12-02 11:35

    try:

    public ActionResult Index() {
        return RedirectToAction("actionName");
        // or
        return RedirectToAction("actionName", "controllerName");
        // or
        return RedirectToAction("actionName", "controllerName", new {/* routeValues, for example: */ id = 5 });
    }
    

    and in .cshtml view:

    @Html.ActionLink("linkText","actionName")
    

    OR:

    @Html.ActionLink("linkText","actionName","controllerName")
    

    OR:

    @Html.ActionLink("linkText", "actionName", "controllerName", 
        new { /* routeValues forexample: id = 6 or leave blank or use null */ }, 
        new { /* htmlAttributes forexample: @class = "my-class" or leave blank or use null */ })
    

    Notice using null in final expression is not recommended, and is better to use a blank new {} instead of null

    0 讨论(0)
  • 2020-12-02 11:35

    You can use local redirect. Following codes are jumping the HomeController's Index page:

    public class SharedController : Controller
        {
            // GET: /<controller>/
            public IActionResult _Layout(string btnLogout)
            {
                if (btnLogout != null)
                {
                    return LocalRedirect("~/Index");
                }
    
                return View();
            }
    }
    
    0 讨论(0)
提交回复
热议问题