代码之家  ›  专栏  ›  技术社区  ›  TheCloudlessSky

动作呈现第一个调用的动作的视图(当一个动作调用另一个动作时)

  •  0
  • TheCloudlessSky  · 技术社区  · 15 年前

    这个名字很可能让人困惑。我有一个要求,其中一个网址必须是友好的名称来表示日期( schedule/today schedule/tomorrow 等等)。我 想把我的路线图弄得乱七八糟吗 DateTime.Now DateTime.Now.AddDays(1) 等不同的参数,所以我决定创建映射到同名操作的路由:

    routes.MapRoute(RouteNames.ScheduleToday, "schedule/today", new { controller = "Schedule", action = "Today" });
    routes.MapRoute(RouteNames.ScheduleTomorrow, "schedule/tomorrow", new { controller = "Schedule", action = "Tomorrow" });
    

    Today() 但实际上 List(DateTime date) 行动,例如, 日期时间。现在 作为 date 参数。

    它的工作原理如下:

    public ActionResult Today()
    {
        return this.List(DateTime.Now);
    }
    
    public ViewResult List(DateTime date)
    {
        this.ViewData["Date"] = date;
        return this.View("List");
    }
    

    我想打电话给你 this.View() 而不是 this.View("List") . 这可能不是我上面所说的吗?似乎呈现的视图与 第一 List 查看。

    3 回复  |  直到 15 年前
        1
  •  1
  •   Steve Michelotti    15 年前

    我不知道如何使无参数View()返回与第一个操作方法的名称匹配的视图以外的其他视图。但是这种解决问题的方法呢 没有 放日期时间。现在在路由映射中-如果您这样定义路由映射:

    routes.MapRoute(RouteNames.ScheduleToday, "schedule/today", new { controller = "Schedule", action = "List", identifier = "today" });
    routes.MapRoute(RouteNames.ScheduleTomorrow, "schedule/tomorrow", new { controller = "Schedule", action = "List", identifier = "tomorrow" });
    

    单一的 路线如下:

    routes.MapRoute(RouteNames.ScheduleToday, "schedule/{identifier}", new { controller = "Schedule", action = "List" });
    

    但在这种情况下,您可能希望路由约束将{identifier}标记约束为仅支持的有效值。有了这些路由,您只需创建一个自定义ActionFilterAttribute 只负责设定日期

    像这样:

    public class DateSelectorAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var identifier = filterContext.RouteData.Values["identifier"] as string;
            switch (identifier)
            {
                case "today":
                    filterContext.ActionParameters["date"] = DateTime.Now;
                    break;
                case "tomorrow":
                    filterContext.ActionParameters["date"] = DateTime.Now.AddDays(1);
                    break;
            }
        }
    }
    

    现在,List()方法可以如下所示:

    [DateSelector]
    public ActionResult List(DateTime date)
    {
        this.ViewData.Model = date;
        return this.View();
    }
    

    顺便说一句,我意识到日期时间。现在在路由中无论如何都不会工作,因为只有在应用程序启动时才会调用它,从而有效地缓存日期值。动作过滤器是一个更好的方法,因为它被称为实时的,给你准确的日期。

        2
  •  0
  •   mare    15 年前

    你所做的是错误的,你重定向到另一个控制器动作从 Today() . 你应该用一个 RedirectToAction() List() 行动。您可以将DateTime作为路由值提供给 重定向到操作() .

        3
  •  0
  •   TheCloudlessSky    15 年前

    我还是找不到 为什么? 行动(也许我会深入了解来源)。暂时我会坚持我所拥有的,因为没有理由把事情复杂化。