2010-09-08 54 views
0

這個名字很可能會讓人困惑。我有一個要求URL必須是名稱友好的以表示日期(schedule/today,schedule/tomorrow等)。我想搞亂我的路線映射與DateTime.NowDateTime.Now.AddDays(1)等不同的參數,所以我決定創建一個映射到同一個名稱的行動路線:動作呈現第一個叫做Action的視圖(當一個動作叫另一個動作時)

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)操作,例如DateTime.Now作爲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視圖。

回答

0

我仍然無法找到爲什麼被稱爲第一動作的觀點,而不是最後動作(或許,我將深入到源)相匹配。暫時我會堅持我所擁有的,因爲沒有理由過分複雜的事情。

1

我不知道有什麼辦法可以使無參數View()返回一個視圖,而不是匹配第一個操作方法名稱的視圖。但對這種做法該怎麼解決您的問題沒有把DateTime.Now在你的路線映射 - 如果你像這樣定義路線映射:

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

但在這種情況下,你會希望有一個路由約束你吱標識符衝令牌限制爲僅支持您有效值。有了這些路線,您可以簡單地創建一個自定義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(); 
} 

而作爲一個側面說明,我在實現建立DateTime.Now路線不管用,因爲這隻會在應用程序啓動時被調用,從而有效地緩存日期值。動作過濾器是一種更好的方法,因爲它被實時調用併爲您提供準確的日期。

希望這會有所幫助。

+0

是的,謝謝你的想法,但我認爲它真的太過複雜了,需要做什麼。調用'this.View(「List」)'就足夠了。 – TheCloudlessSky 2010-09-09 01:08:27

0

你在做什麼是錯誤的,你重定向到另一個控制器動作從Today()。您應該使用RedirectToAction()重載之一。這樣您就不必在List()操作中指定視圖。並且您可以提供DateTime作爲到RedirectToAction()的路由值。

+0

是的,我也試過,但問題是,它實際上會重定向的URL,並將日期*放在* URL(這是醜陋的,因爲我想讓他們友好)。 – TheCloudlessSky 2010-09-09 13:14:42

相關問題