2013年5月5日 星期日

Add Constraint for URL Routing

Example 1: http://localhost/About

routes.MapRoute(
name: "About",
url: "{action}/{id}",
defaults: new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
},
//constraints: new { action = "About" }
constraints: new { action = "(About|Contact)" }
);


 


Example 2: http://localhost/Contact?page=1

RouteTable.Routes.GetVirtualPathForArea(
Request.RequestContext,
new RouteValueDictionary(
new { page = 1 }
)
).VirtualPath;

 


Example 3:


In View:


@(ViewContext.RouteData.Values[“action”]);


@(ViewContext.RouteData.Values[“controller”]);


@(ViewContext.RouteData.Values[“id”]);


 


In Controller:


var currentAction = RouteData.Values[“action”];


var currentController = RouteData.Values[“controller”];


object currentArea;


RouteData.DataTokens.TryGetValue(“area”, out currentArea);


 


Additional Note:


1. A tool to show which route has been used, RouteDebugger


2. Turn off RouteDebugger after installed by changing RouteDebugger:Enabled to false in Web.config

沒有留言:

張貼留言