2012-12-11 44 views
0

我在布局页面中有一个按钮,它应该在不同视图之间导航。将请求重定向到不同的控制器

<a id="next" href="/[email protected]">Next</a> 

我在填充每一页的视图模型ViewBag.CurrentPage值。

导航控制器拦截锚点击以下中的控制器 -

public class NavigationController : Controller 
{ 
    public void Index(string CurrentPage) 
    { 
     PageType currentPageEnum = (PageType)Enum.Parse(typeof(PageType), CurrentPage); 
     PageType nextPageEnum = currentPageEnum + 1; 
     RedirectToAction(nextPageEnum.ToString());    
    } 
} 

枚举包含顺序ActionNames,所以只是增加currentPageEnum值来查找下一个页面。

enum PageType 
{ 
    Page1, 
    Page2 
} 

每个动作在Global.asax.cs中的映射路径如下 -

routes.MapRoute("Page1", "Page1", new { controller="controller1", action="Page1"}); 
routes.MapRoute("Page2", "Page2", new { controller="controller2", action="Page2"}); 

问题: 我一直无法重定向到这个其他控制器代码 -

RedirectToAction(nextPageEnum.ToString()); 

请求终止而不重定向。

  1. 什么信息我错过了。
  2. 是否有导航不同势视图之间 ,在ASP MVC

由于更好的有效的方法!

回答

4

添加一个return语句并使该函数返回一些内容。


public class NavigationController : Controller 
{ 
    public ActionResult Index(string CurrentPage) 
    { 
     PageType currentPageEnum = (PageType)Enum.Parse(typeof(PageType), CurrentPage); 
     PageType nextPageEnum = currentPageEnum + 1; 
     return RedirectToAction(nextPageEnum.ToString());    
    } 
} 

而且因为你是指一个映射路径名称,而不是一个行动,我相信你需要RedirectToRoute而不是RedirectToAction像这样的代码:


public class NavigationController : Controller 
{ 
    public ActionResult Index(string CurrentPage) 
    { 
     PageType currentPageEnum = (PageType)Enum.Parse(typeof(PageType), CurrentPage); 
     PageType nextPageEnum = currentPageEnum + 1; 
     return RedirectToRoute(nextPageEnum.ToString());    
    } 
} 

但我建议最好的方式来浏览在(剃刀)视图的MVC环境中是这样的:

<div> 
    @Html.ActionLink(string linkText, string actionName) 
</div> 

如果操作位于同一控制器中。如果不使用此重载:

<div> 
    @Html.ActionLink(string linkText, string actionName, string controllerName) 
</div> 
+0

谢谢,它帮助。这种方法是最好的在MVC中实现导航的方法。 – Abhijeet

+0

@autrevo我添加了从视图本身导航的最佳方式。 – SynerCoder

0

是的,有如下的有效途径:

只使用

RedirectToAction("ACTION_NAME", "Controller_NAME"); 
相关问题