【问题标题】:ASP.NET MVC 2 Url Format IssueASP.NET MVC 2 URL 格式问题
【发布时间】:2010-08-10 16:25:33
【问题描述】:

我有一个访客控制器。在里面我有索引和登录操作。以下是操作:

  public ActionResult Index(int month,
                              int day,
                              int year){

        var visitors = visitorRepoistory.FindVisitorsByDate(month, day, year).ToList();

        return View("Index", visitors);
    }

    [HttpPost]
    public ActionResult SignIn(Visitor visitor) {
        if (ModelState.IsValid) {
            visitorRepoistory.Add(visitor);
            visitorRepoistory.Save();
            return RedirectToAction("/", new { month = DateTime.Now.Month, day = DateTime.Now.Day, year = DateTime.Now.Year });
        } else {
            return View(new VisitorFormViewModel(visitor));
        }
    }

更具体地说,我试图理解 SignIn() 中的 RedirectToAction()。我想让它重定向到我的索引操作并让 url 看起来像:.../08/10/2010,但我得到的是:?month=8&day=10&year=2010。我该如何解决这个问题?

谢谢。

更新 这是我的路线(当它在 url 中硬编码时):

 routes.MapRoute(
            "VisitorsByDate", // Route name
            "{controller}/{month}/{day}/{year}", // URL with parameters
            new { controller = "visitors", action = "index"}, // Parameter defaults
            new { month = @"\d{2}", day = @"\d{2}", year = @"\d{4}" }
        );

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2


    【解决方案1】:

    您是否有将这些值与路由值匹配的路由?如果您没有匹配的路由,.NET MVC 将以老式(??)格式显示您的参数,而不是像/home/blog/8/10/2010这样的好路径

    routes.MapRoute("Visitor_Routes",  
                    "{controller}/{action}/{month}/{day}/{year}", 
                    new {  
                          controller = "Blog", 
                          action = "archive", 
                          year = Urlparameter.Optional, 
                          month = Urlparameter.Optional, 
                          day = Urlparameter.Optional
                        }); 
    

    【讨论】:

    • 我的路线看起来像这样,当硬编码 url 时,它按应有的方式工作: routes.MapRoute( "VisitorByDate", // 路线名称 "{controller}/{month}/{day}/ {year}", // 带有参数的 URL new { controller = "visitors", action = "index"}, // 参数默认值 new { month = @"\d{2}", day = @"\d{2 }", 年份 = @"\d{24}" } );
    • 啊...原来我的月份 (DateTime.Now.Day) 只是一个整数,这就是为什么路线没有被选中的原因。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 2012-12-29
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多