我有一个名为Diary
的控制器,其操作名为View
。asp.net mvc - 如何在路由中配置默认参数
如果我接收的URL的形式“日记/ 2012/6”我希望它调用View
行动year
= 2012和month
= 6
如果我的形式接收的URL“日记“我希望它通过year
= [当前年份]和month
= [当前月份号码]调用View
行动。
我该如何配置路由?
我有一个名为Diary
的控制器,其操作名为View
。asp.net mvc - 如何在路由中配置默认参数
如果我接收的URL的形式“日记/ 2012/6”我希望它调用View
行动year
= 2012和month
= 6
如果我的形式接收的URL“日记“我希望它通过year
= [当前年份]和month
= [当前月份号码]调用View
行动。
我该如何配置路由?
在你的路线,你可以使用以下命令:
routes.MapRoute(
"Dairy", // Route name
"Dairy/{year}/{month}", // URL with parameters
new { controller = "Dairy", action = "Index", year = DateTime.Now.Year, month = DateTime.Now.Month });
如果不能提供一年/月,当前值将被发送。如果提供它们,那么这些值将被该路线使用。
EDIT
除下面的评论外,这是用于使用上述标准创建新项目的代码。
的Global.asax
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"Dairy/{year}/{month}", // URL with parameters
new { controller = "Dairy", action = "Index", year = DateTime.Now.Year, month = DateTime.Now.Month } // Parameter defaults
);
}
DairyController
public ActionResult Index(int year, int month)
{
ViewBag.Year = year;
ViewBag.Month = month;
return View();
}
观
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
Month - @ViewBag.Month <br/>
Year - @ViewBag.Year
结果:
routes.MapRoute(
"DiaryRoute",
"Diary/{year}/{month}",
new { controller = "Diary", action = "View", year = UrlParameter.Optional, month = UrlParameter.Optional }
);
和控制器动作:
public ActionResult View(int? year, int? month)
{
...
}
如果我不提供URL中的参数,我会得到旧的'参数字典包含空条目'schtick。 – David
@大卫 - 你有其他路线可能会与这一个?我刚刚使用上述方法创建了一个新项目,并且与参数字典没有任何问题。 – Tommy
哦,有趣。我会删除我的其他路线并检查。 – David