我正在使用MVC并尝试通过我的网址传递日期。如果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);
}
我的问题是当我输入网址时:“http://localhost:52159/Articles/Date/09-08-2016”该方法仍然默认为今天的日期。不知道哪里出错了。我觉得它与TryParseExact()有关。
提前致谢!
答案 0 :(得分:1)
您需要路由参数或访问此操作,例如http://localhost:52159/Articles/Date?date=09-08-2016“
RouteConfig中的示例:
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 }
);
}