Action Selector

February 28, 2018 0 Comments A+ a-

ASP .Net

Action Selector:

Action Selectors are the attributes that can be applied to the action methods in MVC application.
Those are helping routing engine to select the appropriate action method from MVC controller to handle the specific request.
There are three types of action selectors attributes.
  • ActionName
  • NonAction
  • ActionVerbs

Action Method in MVC Framework

February 27, 2018 0 Comments A+ a-

ASP .Net

Action method:

Now You will discuss about the action method of controller.
  • Action method must be public.
  • It cannot be private or protected.
  • It cannot be overloaded and static method.
  • It cannot be an extension method.
  • It cannot have open generic types.
  • It contain ref or out parameters
  • It can process the logic and Error handling.

Controller in MVC Framework

February 26, 2018 0 Comments A+ a-

ASP .Net

Controller :


  • In ASP.NET MVC, a Controller handles any incoming URL request and responsible for returning the response to that request.
  • It is used to define and group a set of actions.
  • allowing common sets of rules such as routing, caching, authorization etc to be applied on controller or action.
  • Incoming requests are mapped to actions through routing.
  • It inherit from Microsoft.AspNet.MVC.Controller namespace.
  • Every controller class name must suffix with a word "Controller".
  • Controller is processed incoming request by the help of actions.

Advance Routing in MVC Framework

February 25, 2018 0 Comments A+ a-

ASP .Net

Multiple Routes:

Route customization is an advance topic. In this session we will look at customize the multiple routing in MVC application. You can configure the multiple routes using Map Route extension method in RouteConfig.cs. This method needs at least two parameters such as route name and URL pattern and URL parameter is optional. If you need to pass some value to action using parameter then parameter is mandatory.
While requested URLs comes to application. It is start compared to route patters in order the pattern sequence in the route dictionary or order of added the route in RouteConfig.cs file. If request URLs matched with first URL pattern of the route dictionary, then it will call specified controller and action. In case if URL is not matched with pattern of the route dictionary, then it will call default map route method and executed the default controller and action. Similarly you can able to your own route map in routeconfig.cs file.
Example -1
Route Configuring:
 
       public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");           
   routes.MapRoute(
                name: "EmployeeDetails", 
                url: "EmployeeDetails/{id}",
                defaults: new { controller = "Employee", action = "Details", id = UrlParameter.Optional }
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

Attribute Routes:
 
       [Route("EmployeeDetails/{id}")]
public ActionResult EmployeeDetailsbyID(int id)
  {
  }
How to enable Attribute Routes in MVC application ?

  • You must have enable attribute route in routeconfig.cs file. 
  • It must be enable before the default route.

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }
            );
        }

Pass Multiple Parameter to MVC Action:

Now we will discuss multiple parameter pass to action. you can define the rules in routeconfig.cs file and also attribute route.
For example, the following route applies a multiple parameter pass to action.
Route Configuring:
Example - 2
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute( 
   "EmployeeByJoinDate",
   "Employee/Join/{year}/{month}",
   new { controller = "Employee", action = "EmployeeByJoinDate"}
        }
Attribute Routes:
In this case you can also apply the rules in controller on attribute level.
Example - 3
      
[Route("Employee/Join/{year}/{month}")]
public ActionResult EmployeeByJoinDate(int year, int month)
  {
  }
Above both example will work as same.

Route Constraints:

It will restrict the value of parameter by configuring route constraints and attribute route constraints.
Route Configuring:
Example - 4
public static void RegisterRoutes(RouteCollection routes)        {
            routes.MapRoute( 
   "EmployeeByJoinDate",
   "Employee/Join/{year}/{month}",
   new { controller = "Employee", action = "EmployeeByJoinDate"},
   new { year = @"\d{4}", month = @"\d{2}"}
        }
Attribute Routes:
Example - 5
      
[Route("Employee/Join/{year:regex(\\d{4})}/{month:regex(\\d{2})}")]
 public ActionResult EmployeeByJoinDate(int year, int month)
  {
  }
ConstraintDescriptionExample
alphaMatches uppercase or lowercase Latin alphabet characters (a-z, A-Z){x:alpha}
boolMatches a Boolean value.{x:bool}
datetimeMatches a DateTime value.{x:datetime}
decimalMatches a decimal value.{x:decimal}
doubleMatches a 64-bit floating-point value.{x:double}
floatMatches a 32-bit floating-point value.{x:float}
guidMatches a GUID value.{x:guid}
intMatches a 32-bit integer value.{x:int}
lengthMatches a string with the specified length or within a specified range of lengths.{x:length(6)}
{x:length(1,20)}
longMatches a 64-bit integer value.{x:long}
maxMatches an integer with a maximum value.{x:max(10)}
maxlengthMatches a string with a maximum length.{x:maxlength(10)}
minMatches an integer with a minimum value.{x:min(10)}
minlengthMatches a string with a minimum length.{x:minlength(10)}
rangeMatches an integer within a range of values.{x:range(10,50)}
regexMatches a regular expression.{x:regex(^\d{3}-\d{3}-\d{4}$)}

Route Prefixes:

You can set a common prefix for an entire controller by using the [RoutePrefix] attribute.
Use a tilde (~) on the method attribute to override the route prefix.
Example - 6
[RoutePrefix("Employee/Details")]
public class EmployeeController : Controller
{
// GET Employee/Details
    [Route("")] 
    public IEnumerable EmployeeDetails() { ... }
 
//Employee/Details/12
    [Route("{id:int}")] 
    public EmployeeModels EmployeeDetailsByID(int id) { ... }

//employeemodels/Employee/Join/2018/02
    [Route("~/Employee/Join/{year:regex(\\d{4})}/{month:regex(\\d{2})}")]  
    public HttpResponseMessage EmployeeByJoinDate(int year, int month) { ... }
}

Warm up

  • Configure the multiple routes using Map Route extension method in RouteConfig.cs.
  • Pass multiple parameter to action by using Route Configuring or Attribute Routes.
  • Restrict the value of parameter using Route Constraints on Route Configuring or Attribute Routes.
  • You can set a common prefix for an entire controller by using the [RoutePrefix] attribute.
  • Use a tilde (~) on the method attribute to override the route prefix.