Wednesday 20 May 2015

ASP.Net MVC Routing With Example

Here we will learn Asp.net MVC Routing with an example. Routing is a process of mapping the controller and action method through which a view is use for user as an output. Basically Routing work for an URL or we it is a  Restful URL.
This URL is understand at the Run time means when controller loads and execute action method then t decide URL or view that which screen have to show to user. Whenever a user make a request related to page then it load the page then it transfer this page request to the user’s browser via all the page life cycle. Here .aspx page and .aspx.cs page both are bind with this so when it render user request then this asp.net MVC load both the pages.
Here we will understand Asp.net MVC Segment, ASP.Net MVC 3 type of Segment 
  1. Controller Segment 
  2. Action Segment
  3. Parameter Segment 
In your application app_start folder you will see a class as “RouteConfig.cs” class contain a function as ” RegisterRoutes” Right click on this and go to this definition .
RouteConfig.cs method
 protected void Application_Start() 
      { 
          AreaRegistration.RegisterAllAreas(); 
 
          WebApiConfig.Register(GlobalConfiguration.Configuration); 
          FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
          RouteConfig.RegisterRoutes(RouteTable.Routes); 
          BundleConfig.RegisterBundles(BundleTable.Bundles); 
      }


When you will go on this method this will go to Register
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;


namespace MvcApplication

{

    public class RouteConfig

    {

        public static void RegisterRoutes(RouteCollection routes)

        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(

                name: "Default",

                url: "{controller}/{action}/{id}",

                defaults: new { controller = " Home ", action = "Index", id = UrlParameter.Optional }
            );

        }

    }

}

     Here it contain default controller as Home and action as Index and here parameter as optional you can change all these thing means you can call your method which is created in your controller , you also can change your controller as I did in  “Controller in MVC application” tutorial.
Controller Segment : -  Controller is basically a view name that is used to show the data  to the user , it is used to handling user request and response. We can create our controller , these controller are stored in Controller class , for example we create HomeController.cs. All the controller are inherited from the base controller class.
This home controller class contain two type  controls As index and about
using System.Web.Mvc;

namespace MVCController
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}

public ActionResult About()
{
return View();
}
}
}

Action Segment : - You can follow this link for this  “Action Result and action method”
Parameter Segment : - you can follow this link “Controller in MVC
Asp.net MVC Routing : -  Routing is the most important feature of Asp.net MVC , because this the modal which is responsible for mapping for user request and for response to specific controller and method.
This routing data is filled in Application_start event (means this method contain “.RegisterRoutes(RouteTable.Routes);  “ )  it uses Route table object for filling the data,
Route engine is used to matching the incoming request and execute action method.

Customizing Routing in ASP.NET MVC :-  we are able  customize our default route of execution. Mostly all the MVC application use default route for execution but sometimes we need to customizing  this default route. There are some example for customize route,
If URL is date then we need specific format like 11-05-2015   , if url contain integer ID then we need to customize this.
Attribute Routing : -  This is a new type of Routing which is introduced  in Asp.net MVC 5. Attribute routing uses attributes for creating Routes. Basically Attribute routing gives us more control for handling URL by adding routes directly to controller and actions
This Routing should be register in “RegisterRoutes” method of Global.asax or in RoutCnfig.cs file. This routing should be configures before the convention based routing
This following code shows us that  how to register a Attribute Routing
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        //Add the following line
        routes.MapMvcAttributeRoutes();  
        //convention based routes
    }
}
If we are using both Attribute routing and convention based routing then actions which are configured for attribute routing will work as per attribute routes and the actions which are not configured will work as convention based routes.
Routing Constraints : - Routing constrains allow us to use validation on the define route. Routing constrains enable user to prevent for getting route map with the user request unless specific validation matched.
Ex user request should be matched with particular route only if ID is parameter and the type is int.
Following is the code for defining creates routes with the constraints which allow us to integer value as ID Parameters.
routes.MapRoute("Default", // Route name
    "{controller}/{action}/{id}", // Route Pattern
    new { controller = "Orders", action = "GetOrder",
            id = UrlParameter.Optional }, // Default values for parameters
    new { id = @"\d+" } //Restriction for id
    );
If we need more complex validation, we can implement "IRouteConstraint" interface and  use Match method to implement logic.
follwoing code creates a  custom route constraints by implementing "IrouteConstraint". that checks whether provided parameter is valid  or not.
public class DateConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, 
        string parameterName, RouteValueDictionary values,
                 RouteDirection routeDirection)
    {
        DateTime dt;
 
        return DateTime.TryParseExact(values[parameterName].ToString(), 
        "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
    }
}
Area Registration : -
Area is a feature of MVC2. this allows us  to create our applications in bgood way. Ex  we have billing application we may have different parts like Billing, Admin, , Order and so on. We  will create different Area for each and every part. Every area will contain Views.
we can register specific area by inherting "AreaRegistration" class
following code shows us that  how to register Admin Area.
public class HelpDeskAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        { 
            return "Admin";
        }
    }
}
  
public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "admin_default",
        "admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}
            






No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...