我正在使用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"]); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。