Tuesday, November 11, 2014

Routing in MVC Asp.net

Routing means to map the url to resources. Routing and url rewrite both are different. Url rewrite   mapping the url to new url.  In an ASP.NET we have not use routing, an incoming request for a URL typically maps to a physical file on disk such as an .aspx file. In routing MVC you have to define route. In a route, you specify placeholders that are mapped to values that are parsed from the URL request. You can also specify constant values that are used for matching URL requests. So here is example given below.
In asp.net mvc by default route is defined. You have check in mvc application App_start folder here RouteConfig.cs file

routes.MapRoute(
               name: "Default",
               url: "{controller}/{action}/{id}",
               defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
           );
                                
Here “Name” is root name
   “url” "{controller}/{action}/{id}", anonymous object with three properties, id  is optional
Suppose we have create new method in home controller as given below
public ActionResult CategoriesList(string CategoryName)
        {


           
            return View();
        }
When we call this url “/home/CategoriesList/games”.  When called this url, you will know categoryname parameter is coming null.  This is because the default route has specified a parameter called {id} but no {id} parameter was available in the Controller method.
So you have to run this, you need to create new root RouteConfig.cs file is given below

  



routes.MapRoute(
               name: "HomeCat",
               url: "{controller}/{action}/{CategoryName}",
               defaults: new { controller = "Home", action = "Index", CategoryName = UrlParameter.Optional }
           );

            routes.MapRoute(
               name: "Default",
               url: "{controller}/{action}/{id}",
               defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
           );
So  you have declare “HomeCat” root above the “default” root.

No comments:

Post a Comment

http://blogsiteslist.com