如何在ViewResult或ActionResult函数中重定向?

时间:2021-05-16 21:07:38

Say I have:

说我有:

public ViewResult List() 
{
    IEnumerable<IModel> myList = repository.GetMyList();
    if(1 == myList.Count())
    {
        RedirectToAction("Edit", new { id = myList.Single().id });
    }

    return View(myList);
}

Inside this function, I check if there is only one item in the list, if there is I'd like to redirect straight to the controller that handles the list item, otherwise I want to display the List View.

在这个函数中,我检查列表中是否只有一个项目,如果有我想直接重定向到处理列表项的控制器,否则我想显示列表视图。

How do I do this? Simply adding a RedirectToAction doesn't work - the call is hit but VS just steps over it and tries to return the View at the bottom.

我该怎么做呢?简单地添加RedirectToAction不起作用 - 调用被命中,但VS只是跨过它并尝试返回底部的视图。

1 个解决方案

#1


23  

You need to return RedirectToAction instead of just calling the RedirectToAction method. Also, your method will need to return an ActionResult is a return type compatible with both ViewResult and RedirectToRouteResult.

您需要返回RedirectToAction而不是仅调用RedirectToAction方法。此外,您的方法将需要返回一个ActionResult是一个与ViewResult和RedirectToRouteResult兼容的返回类型。

public ActionResult List() 
{
    IEnumerable<IModel> myList = repository.GetMyList();
    if(1 == myList.Count())
    {
        return RedirectToAction("Edit", new { id = myList.Single().id });
    }

    return View(myList);
}

#1


23  

You need to return RedirectToAction instead of just calling the RedirectToAction method. Also, your method will need to return an ActionResult is a return type compatible with both ViewResult and RedirectToRouteResult.

您需要返回RedirectToAction而不是仅调用RedirectToAction方法。此外,您的方法将需要返回一个ActionResult是一个与ViewResult和RedirectToRouteResult兼容的返回类型。

public ActionResult List() 
{
    IEnumerable<IModel> myList = repository.GetMyList();
    if(1 == myList.Count())
    {
        return RedirectToAction("Edit", new { id = myList.Single().id });
    }

    return View(myList);
}