开发者

How do I redirect within a ViewResult or ActionResult function?

Say I have:

public ViewResult List() 
{
    IEnumerable<IModel> myList = repository.GetMyList();
    if(1 == myList.Count())
    {
        RedirectToAction("Edit", new { id = myList.S开发者_开发知识库ingle().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.


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.

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

    return View(myList);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜