如何使用路由和/或查询字符串数据启动页面?

时间:2012-04-19 18:45:05

标签: asp.net-mvc asp.net-mvc-3 routes query-string asp.net-mvc-routing

首次加载页面时,网址如下所示:http://localhost:1245/。但是,我希望它看起来像这样:http://localhost:1245/Home/Index/2/2012?Events=Show(/ 2/2012?Events = Show是重要的部分)。如何从一开始就使用第二个URL加载我的页面?

2 个答案:

答案 0 :(得分:2)

我要做的是在默认MVC路由之前添加一个新路由,使其看起来像:

routes.MapRoute(
  "NewDefault", // Route name
  "{controller}/{action}/{month}/{year}", // URL with parameters
  new { controller = "Events", 
        action = "Shows", 
        month = DateTime.Now.Month,
        year = DateTime.Now.Year } // Parameter defaults
  );

routes.MapRoute(
  "Default", // Route name
  "{controller}/{action}/{id}", // URL with parameters
  new { controller = "Home", 
        action = "Index", 
        id = UrlParameter.Optional } // Parameter defaults
  );

默认网址(从根本上说,对用户不可见)为/Events/Shows/4/2012(如果日期为4/19/2012)。默认控制器为EventsController,默认操作为EventsController.Shows

public EventsController
{
  public ActionResult Shows(int month, int year)
  {
    someModel model = new someModel();
    someModel.month = month;
    someModel.year = year;
    this.View(someModel);
  }
}

答案 1 :(得分:1)

添加:

  routes.MapRoute("MyRouteName", 
    "Home/Index/2/2012", new { controller = "Home", action = "Index" });

到你的路线。

将HomeController的Index操作更改为具有以下签名:

public ActionResult Index(string Events)....