2016-09-09 3 views
0

MVC에서 일하고 있으며 내 URL을 통해 날짜를 전달하려고합니다. URL에 날짜가 제공되지 않으면 메소드가 오늘 날짜로 기본 설정됩니다. "http://localhost:52159/Articles/Date/09-08-2016"방법은 여전히 ​​오늘 날짜로 디폴트됩니다 : 나는 URL을 입력 할 때내 변수가 왜 이상한지 확실하지 않음

public ActionResult Date(string date) 
    { 
     DateTime searchDate = DateTime.Now.Date; 
     bool success = false; 

     if(date != null) 
     { 
      success = DateTime.TryParseExact(date, "MM-dd-yyyy", System.Globalization.CultureInfo.CurrentCulture, 
         System.Globalization.DateTimeStyles.AllowWhiteSpaces, out searchDate); 
     } 

     List<Article> articles = new List<Article>(); 

     foreach (Article a in db.Articles) 
     { 
      if (a.PostedDateTSU.Value.Day == searchDate.Day && a.PostedDateTSU.Value.Month == searchDate.Month && 
       a.PostedDateTSU.Value.Year == searchDate.Year) 
      { 
       articles.Add(a); 
      } 
     } 
     return View(articles); 
    } 

내 문제입니다. 어디서 잘못 될지 잘 모릅니다. TryParseExact()와 관련이 있다는 느낌이 들었습니다.

미리 감사드립니다.

+0

조금 디버그 포인트 또는 메시지를 넣어 거기에 심지어 TryParseExact() 도달하는지 확인하십시오. – WBT

+2

날짜가 왜'DateTime' 대신'string'을 사용합니까? –

+0

@StephenMuecke URL없이 추가 가능하지 않은 DateTime 형식을 전달할 수 있다고 생각하지 않습니다. 그럴 수 있겠습니까? –

답변

1

당신은 RouteConfig이 http://localhost:52159/Articles/Date?date=09-08-2016 "

예처럼 행동 경로에 매개 변수 또는 액세스가 필요합니다?이 후 '성공'의 값이 무엇

public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      name: "DateRoute", 
      url: "{controller}/{action}/{date}", 
      defaults: new { controller = "YourController", action = "Date", date = UrlParameter.Optional } 
     ); 

     routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
      ); 

    } 
+0

그게 작동하지 않습니다 (모든 것이 이제 DateRoute와 일치하고 Default 라우트는 절대로 안타를 것입니다). DateRoute은'url : "기사/날짜/{date}"및'defaults : new {controller = "Articles", action = "Date"}' –

관련 문제