加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – RedirectToAction替代方案

发布时间:2020-12-16 06:54:30 所属栏目:asp.Net 来源:网络整理
导读:我正在使用ASP.NET MVC 3. 我按照以下方式编写了一个帮助类: public static string NewsList(this UrlHelper helper){ return helper.Action("List","News");} 在我的控制器代码中我使用它像这样: return RedirectToAction(Url.NewsList()); 所以在重定向
我正在使用ASP.NET MVC 3.

我按照以下方式编写了一个帮助类:

public static string NewsList(this UrlHelper helper)
{
     return helper.Action("List","News");
}

在我的控制器代码中我使用它像这样:

return RedirectToAction(Url.NewsList());

所以在重定向之后,链接看起来像这样:

../News/News/List

RedirectToAction有替代品吗?有没有更好的方法来实现我的帮助方法NewsList?

解决方法

其实你真的不需要帮手:

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"]);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读