【问题标题】:RedirectToAction alternativeRedirectToAction 替代
【发布时间】:2011-02-01 14:26:36
【问题描述】:

我正在使用 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?

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    其实你并不需要帮助者:

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

    【讨论】:

    • @Darin:我想尝试尽可能多地消除硬编码,这就是我想创建一个辅助方法的原因。是否可以像我上面尝试的那样在辅助方法中使用 MVCContrib 的方式?
    • @Brendan,是的,你可以简单地编写一个BaseController 的扩展方法(与MVCContrib 的RedirectToAction&lt;TController&gt; 相同),它将重定向结果返回到新闻控制器的列表操作,然后使用它在你的控制器中是这样的:return this.RedirectToNewsList();.
    • @Daring:我还发现的另一件事是在我的创建新闻页面上,我有一个取消按钮。如果单击取消按钮,则必须转到列表页面。现在在我的 javascript 代码中,我有以下内容: window.location = '@Url.NewsList()';使用上面建议的代码,它无法正常工作,当我查看源代码时,它看起来像这样: window.location = '{ action = List, controller = News }';使用我的原始代码,它看起来像 window.location = '/News/List';
    • 您也可以使用window.location.href = '@Url.RouteUrl(Url.NewsList())';。为了缩短语法,您可以将其封装回扩展方法中。
    • @Brendan,请查看我的更新 2。
    猜你喜欢
    • 2011-03-09
    • 1970-01-01
    • 2012-02-15
    • 2010-09-27
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    相关资源
    最近更新 更多