我正在使用ASP.NET MVC 3.
我按照以下方式编写了一个帮助类:
public static string NewsList(this UrlHelper helper) { return helper.Action("List","News"); }
在我的控制器代码中我使用它像这样:
return RedirectToAction(Url.NewsList());
../News/News/List
解决方法
其实你真的不需要帮手:
return RedirectToAction("List","News");
或者如果你想避免硬编码:
public static object NewsList(this UrlHelper helper) { return new { action = "List",controller = "News" }; }
然后:
return RedirectToRoute(Url.NewsList());
或另一种可能性是使用MVCContrib,它允许你写下面的内容(个人这就是我喜欢和使用的):
return this.RedirectToAction<NewsController>(x => x.List());
或另一种可能性是使用T4 templates.
因此,你可以自己选择和玩.
更新:
public static class ControllerExtensions { public static RedirectToRouteResult RedirectToNewsList(this Controller controller) { return controller.RedirectToAction<NewsController>(x => x.List()); } }
然后:
public ActionResult Foo() { return this.RedirectToNewsList(); }
更新2:
NewsList扩展方法的单元测试示例:
[TestMethod] public void NewsList_Should_Construct_Route_Values_For_The_List_Action_On_The_News_Controller() { // act var actual = UrlExtensions.NewsList(null); // assert var routes = new RouteValueDictionary(actual); Assert.AreEqual("List",routes["action"]); Assert.AreEqual("News",routes["controller"]); }