How to Create Custom route using constraint in ASP.NET MVC ?
- In following tutorial,
we will learn that how to create custom routes using Constraint in ASP.Net MVC.
- You use route
constraints to restrict the browser requests that match a particular route. You
can use a regular expression to specify a route constraint.
- Create New ASP.Net
MVC 4 Web Application with “Basic”
Project Template.
- Open [RouteConfig.cs] file from [ App_Start] folder and below [ DateRoute] route exactly above Default route .
Here you can find my demo code :
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//
http://localhost:50399/2014/05/02
routes.MapRoute(
name:
"DateRoute",
url:
"{year}/{month}/{day}",
defaults: new { controller = "Blog", action =
"Index" },
constraints: new { year = @"\d{4}", month =
@"\d{2}", day = @"\d{2}" }
);
// http://localhost:50399/Home/Index
routes.MapRoute(
name:
"Default",
url:
"{controller}/{action}/{id}",
defaults: new { controller = "Home", action =
"Index", id = UrlParameter.Optional }
);
}
Description of above Example ASP.NET MVC code :
- You can see in DateRoute, the URL pattern is [ {year}/{month}/{day}
] and it is using Index action of [ BlogController ].
- You can also see “ DateRoute “ contains a regular expression
constraint that only matches year/month/day URL pattern.
- The regular expression ( \d{4} ) matches four integers which
is year and ( \d{2} )matches two
integers which is month and day.
Now, Create BlogController
and
add Index
action
as shown in below code.
public class BlogController : Controller
{
public ActionResult Index(string year, string month, string day)
{
ViewBag.date = year + "/" + month + "/" + day;
return View();
}
}
Now, you have
to create Index.cshtml view by Right click on BlogController Index action ⇒ Add View ⇒ click Add.
It will look like this :
@{
ViewBag.Title =
"Index";
}
<h2>Index</h2>
<h2>This is the date :
@ViewBag.date</h2>
Now,
Run the project by pressing “F5” from the keyboard and browse thehttp://localhost:50399/2014/05/02
URl, you will get output as shown in
below screenshot.
I hope you may like my Tutorial
Click here for My more post :