【问题标题】:ASP.net MVC RoutesASP.net MVC 路由
【发布时间】:2009-02-04 10:55:51
【问题描述】:

我目前正在创建我公司网站的移动版本,并将其用作学习 asp.net mvc 的时间。

我打算创建的网址如下

工作/在/位置
工作/for/jobTitle
工作/在/位置/for/jobtitle
工作/for/jobtitle/in/位置

现在我们添加的类型越多,我需要添加的路线就越多,我需要的路线也就越多,所以不需要真正维护。

所以目前在我的 Global.asax.cs 中是

//Jobs routes.MapRoute( "DefaultJobs", // Route name "Jobs/{pagenumber}", // URL with parameters new { controller = "Jobs", action = "Default", pagenumber = "1" } // Parameter defaults ); //Jobs by Location routes.MapRoute( "JobsByLocation", // Route name "Jobs/in/{location}/{pagenumber}", // URL with parameters new { controller = "Jobs", action = "Default", location = "", pagenumber = "1" } // Parameter defaults ); //Jobs by Title routes.MapRoute( "JobsByTitle", // Route name "Jobs/for/{title}/{pagenumber}", // URL with parameters new { controller = "Jobs", action = "Default", title= "", pagenumber = "1" } // Parameter defaults ); //Jobs by Title and Location routes.MapRoute( "JobsByTitleAndLocation", // Route name "Jobs/for/{title}/in/{location}/{pagenumber}", // URL with parameters new { controller = "Jobs", action = "Default", location = "", title = "", pagenumber = "1" } // Parameter defaults );

所以我不确定这是否正确,因为在我的 JobsController 中我确实有“in”作为控制器,但我只能得到一个参数。所以我选择了一个可以捕获所有内容的默认设置。


public ActionResult Default(string location, string title, string pagenumber)
        {
            return Content("Location " + location + " Title " + title + " Page " + pagenumber);
        }

现在这是正确的做法吗?还是我错过了什么?

为了调用这个方法,我有这个


[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SearchContinent(string Continents)
        {
            try
            {
                // TODO: Add update logic here

                //return RedirectToAction("Default","Jobs",
                    //new {
                       // location = Continents
                        // }); 

                return RedirectToRoute(new { controller = "Jobs", action = "Default", location = Continents, pagenumber = "1" });


                //return Redirect("Jobs/in/" + Continents);
            }
            catch
            {
                return View();
            }
        }

现在这不会产生正确的 url,因为它缺少“in”并将“location”作为参数传递,这有效但不正确。

【问题讨论】:

    标签: c# asp.net asp.net-mvc


    【解决方案1】:

    使用 RedirectToRoute 你应该传递你的目标路由名称,所以:

    return RedirectToRoute("JobsByLocation", new { location = Continents, pagenumber = "1" });
    

    【讨论】:

    • 我会将 pagenumber 更改为 int,并删除 SearchContinent 中的 try/catch - 我不确定它在那里的用途。但如果没有其他上下文,就很难说。
    猜你喜欢
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多