MVC 4:自定义路线 [英] MVC 4: Custom Route
问题描述
ASP.NET MVC 4的网站。
得到一个名为位置的数据库表,其中包含只有三个可能的位置(如CA,纽约,AT)
默认路由是:
的http://服务器/位置/ ---位置列表
HTTP:NY-位置//服务器/位置/纽约---细节
如何创建无/位置/自定义路线 - 位?
(我觉得这有点多好听)
这样
的http://服务器/纽约 - 纽约的细节
HTTP://服务器/ AT - AT的细节
....等...
和
的http://服务器/位置---位置列表
一个解决方法是使用路由约束进行定制路线:
(顺序事项)
routes.MapRoute(
名称:城市,
网址:{城市},
限制:新{城市= @\\ w {2}},
默认:新{控制器=位置,行动=详细信息,ID = UrlParameter.Optional}
);routes.MapRoute(
名称:默认,
网址:{控制器} / {行动} / {ID}
默认:新{控制器=家,行动=索引,ID = UrlParameter.Optional}
);
在配套控制器:
公共类LocationController:控制器
{
//
// GET:/位置/
公众的ActionResult指数()
{
返回查看();
} //
// GET:/ {}城市
公众的ActionResult详细信息(字符串市)
{
返回查看(型号:市);
}
}
如果您希望只允许纽约州,加利福尼亚州和AT你可以写你路由约束,如:
的限制,新的城市{= @纽约| CA | AT}
(小写的作品太)。另一个更通用的解决方案,而不是使用路由约束实现的是实现自己的 IRouteConstraint
。硒<一个href=\"http://stackoverflow.com/questions/7570237/mvc-3-routing-help-with-dynamic-route/7570543#7570543\">my previous答案。
ASP.NET MVC 4 website.
Got a database-table named "Locations", which holds only three possible Locations (eg. "CA","NY","AT") The default route would be:
http://server/Location/ --- list of Locations
http://server/Location/NY --- details of NY-Location
How can I create a custom route without the /Location/ - bit? (which I find a bit more nice)
So that
http://server/NY - details of NY
http://server/AT - details of AT
.... etc...
and
http://server/Location --- list of Locations
A solution is to do a custom route using a route constraint: (the order matters)
routes.MapRoute(
name: "City",
url: "{city}",
constraints: new { city = @"\w{2}" },
defaults: new { controller = "Location", action = "Details", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
with the matching controller:
public class LocationController : Controller
{
//
// GET: /Location/
public ActionResult Index()
{
return View();
}
//
// GET: /{city}
public ActionResult Details(string city)
{
return View(model:city);
}
}
If you want to allow only NY, CA and AT you could write you route constraint like:
constraints: new { city = @"NY|CA|AT" }
(lower case works too). Another, more generic solution instead of using a route contraint is to implement your own IRouteConstraint
. Se my previous answer.
这篇关于MVC 4:自定义路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!