Monday, 29 December 2014

ASP.NET URL Routing to MVC format

This is very useful post because if user want to show the url like in below format then how your going to show the below format using ASP.NET

ASP.NET URL : http://localhost/view.aspx?paramtype&param1=value&param2=value&...

ASP.NET MVC : http://localhost/view?paramtype&param1=value&param2=value&...

In order to achieve the MVC Url format using ASP.NET WebForms existing project then go with URL Routing. For this we need the following namespace,

System.Web.Routing

I am going to tell in step by step manner,

Step 1 : First add the System.Web.Routing namespace to project using Add Reference.

Step 2 : Add the following line in Web.Config file, under 
<system.web>
 <compilation defaultLanguage="c#" debug="true">
      <assemblies>
.... 
....

<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />     
 </assemblies>
    </compilation>
</system.web>

Step 3 : Add namespace  System.Web.Routing in Global.asax,cs file

Step 4 :  Call the method RegisterRoutes in Application_Start event

 protected void Application_Start(object sender, EventArgs e)
        {           
            RegisterRoutes(RouteTable.Routes);
        }

Step 5 : Create the event and route the MVC format
 private void RegisterRoutes(RouteCollection routes)
        {
                    routes.MapPageRoute("View", "view/{*extrainfo}", "~/view.aspx", true);
        }

Where, 1st Parameter - Name for routing
2nd parameter : Format for MVC
3rd Parameter - actual page.
4th Parameter - Set to true for routing


That's it,

Happy Coding :)          

No comments:

Post a Comment