Pages

Men

rh

10/13/2014

MVC 4 Interview Questions Part-2

11)  What is difference between 3-layer architecture and MVC architecture?
Ans. 3-layer architecture separates the application into 3 components which consists of Presentation Layer Business Layer and Data Access Layer. In 3-layer architecture, user interacts with the Presentation layer. 3-layer is a linear architecture.


MVC architecture separates the application into three components which consists of Model, View and Controller. In MVC architecture, user interacts with the controller with the help of view. MVC is a triangle architecture.


 
MVC does not replace 3-layer architecture. Typically 3-layer and MVC are used together and MVC acts as the Presentation layer.



Q13. What is ViewModel in ASP.NET MVC?
Ans. In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-typed view. It is used to pass data from controller to strongly-typed view.
Key Points about ViewModel
 ViewModel contain fields that are represented in the view (for LabelFor, EditorFor, DisplayFor helpers)
 ViewModel can have specific validation rules using data annotations.
 ViewModel can have multiple entities or objects from different data models or data source.


Q14. Explain ASP.NET MVC pipeline?
Ans. The detail ASP.NET MVC pipeline is given below:
1. Routing - Routing is the first step in ASP.NET MVC pipeline. Typically, it is a pattern matching system that matches the incoming request to the registered URL patterns in the Route Table.
The UrlRoutingModule(System.Web.Routing.UrlRoutingModule) is a class which matches an incoming HTTP request to a registered route pattern in the RouteTable(System.Web.Routing.RouteTable).


2. Controller Initialization - The MvcHandler initiates the real processing inside ASP.NET MVC pipeline by using ProcessRequest method. This method uses the IControllerFactory instance (default is System.Web.Mvc.DefaultControllerFactory) to create corresponding controller.





3. Action Execution – Action execution occurs in the following steps:
  • When the controller is initialized, the controller calls its own InvokeAction() method by passing the details of the chosen action method. This is handled by the IActionInvoker.
  • After chosen of appropriate action method, model binders(default is System.Web.Mvc.DefaultModelBinder) retrieves the data from incoming HTTP request and do the data type conversion, data validation such as required or date format etc. and also take care of input values mapping to that action method parameters.
  • Authentication Filter was introduced with ASP.NET MVC5 that run prior to authorization filter. It is used to authenticate a user. Authentication filter process user credentials in the request and provide a corresponding principal. Prior to ASP.NET MVC5, you use authorization filter for authentication and authorization to a user.
  • By default, Authenticate attribute is used to perform Authentication. You can easily create your own custom authentication filter by implementing IAuthenticationFilter.
  • Authorization filter allow you to perform authorization process for an authenticated user. For example, Role based authorization for users to access resources.
  •  By default, Authorize attribute is used to perform authorization. You can also make your own custom authorization filter by implementing IAuthorizationFilter.
  • Action filters are executed before (OnActionExecuting) and after (OnActionExecuted) an action is executed. IActionFilter interface provides you two methods OnActionExecuting and OnActionExecuted methods which will be executed before and after an action gets executed respectively. You can also make your own custom ActionFilters filter by implementing IActionFilter. For more about filters refer this article Understanding ASP.NET MVC Filters and Attributes
  • When action is executed, it process the user inputs with the help of model (Business Model or Data Model) and prepare Action Result.

4. Result Execution - Result execution occurs in the following steps:
  • Result filters are executed before (OnResultExecuting) and after (OnResultExecuted) the ActionResult is executed. IResultFilter interface provides you two methods OnResultExecuting and OnResultExecuted methods which will be executed before and after an ActionResult gets executed respectively. You can also make your own custom ResultFilters filter by implementing IResultFilter.
  • Action Result is prepared by performing operations on user inputs with the help of BAL or DAL. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult.
  • Various Result type provided by the ASP.NET MVC can be categorized into two category- ViewResult type and NonViewResult type. The Result type which renders and returns an HTML page to the browser, falls into ViewResult category and other result type which returns only data either in text format, binary format or a JSON format, falls into NonViewResult category.

4.1 View Initialization and Rendering - View Initialization and Rendering execution occurs in the following steps

  • ViewResult type i.e. view and partial view are represented by IView (System.Web.Mvc.IView) interface and rendered by the appropriate View Engine.
  • Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
    www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 21
  • This process is handled by IViewEngine (System.Web.Mvc.IViewEngine) interface of the view engine. By default ASP.NET MVC provides WebForm and Razor view engines. You can also create your custom engine by using IViewEngine interface and can registered your custom view engine in to your ASP.NET MVC application as shown below:
  • Html Helpers are used to write input fields, create links based on the routes, AJAX-enabled forms, links and much more. Html Helpers are extension methods of the HtmlHelper class and can be further extended very easily. In more complex scenario, it might render a form with client side validation with the help of JavaScript or jQuery.

Q15. What is Routing in ASP.NET MVC?
Ans. Routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. At runtime, Routing engine use the Route table for matching the incoming request's URL pattern against the URL patterns defined in the Route table. You can register one or more URL patterns to the Route table at Application_Start event.


 
When the routing engine finds a match in the route table for the incoming request's URL, it forwards the request to the appropriate controller and action. If there is no match in the route table for the incoming request's URL, it returns a 404 HTTP status code.

Q16. How to define a route in ASP.NET MVC?
Ans. You can define a route in ASP.NET MVC as given below:


public static void RegisterRoutes(RouteCollection routes) 

routes.MapRoute
    ( "Default", // Route name "
      {controller}/{action}/{id}", // Route Pattern 
        new 
       {
              controller = "Home", 
              action = "Index", 
              id = UrlParameter.Optional
        }// Default values for above defined parameters 
    ); 

protected void Application_Start() 
  { 
   RegisterRoutes(RouteTable.Routes); 
   //TODO: 
}

Always remember route name should be unique across the entire application. Route name can’t be duplicate.
In above example we have defined the Route Pattern {controller}/{action}/{id} and also provide the default values for controller, action and id parameters. Default values means if you will not provide the values for controller or action or id defined in the pattern then these values will be serve by the routing system.


Suppose your webapplication is running on www.example.com then the url pattren for you application will be www.example.com/{controller}/{action}/{id}. Hence you need to provide the controller name followed by action name and id if it is required. If you will not provide any of the value then default values of these parameters will be provided by the routing system. Here is a list of URLs that match and don't match this route pattern.


Note: Always put more specific route on the top order while defining the routes, since routing system check the incoming URL pattern form the top and as it get the matched route it will consider that. It will not checked further routes after matching pattern.

Q17. What is Attribute Routing and how to define it?
Ans. ASP.NET MVC5 and WEB API 2 supports a new type of routing, called attribute routing. In this routing, attributes are used to define routes. Attribute routing provides you more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API.
 

1. Controller level routing – You can define routes at controller level which apply to all actions within the controller unless a specific route is added to an action.

[RoutePrefix("MyHome")]
[Route("{action=index}")] 
//default action 

public class HomeController : Controller 

  //new route: /MyHome/Index 
           public ActionResult Index() 
          { 
             return View(); 
           } //new route: /MyHome/About 
           public ActionResult About() 
            { 
                ViewBag.Message = "Your application description page."; 
                 return View();
              } //new route: /MyHome/Contact 
             public ActionResult Contact() 
           { 
               ViewBag.Message = "Your contact page."; return View(); 
            } 
}

2. Action level routing – You can define routes at action level which apply to a specific action with in the controller.

public class HomeController : Controller 
{
    [Route("users/{id:int:min(100)}")] //route: /users/100
    public ActionResult Index(int id) 
      {
       //TO DO: return View(); 
       }
        [Route("users/about")] //route" /users/about

       public ActionResult About()
       {
           ViewBag.Message = "Your application description page.";
          return View(); 
        } 
          //route: /Home/Contact 
          public ActionResult Contact() 
            { 
               ViewBag.Message = "Your contact page."; 
                return View();  
             }

Note:
  • Attribute routing should configure before the convention-based routing.
  • When you combine attribute routing with convention-based routing, actions which do not have Route attribute for defining attribute-based routing will work according to convention-based routing. In above example Contact action will work according to convention-based routing.
  • When you have only attribute routing, actions which do not have Route attribute for defining attribute-base

Q18. When to use Attribute Routing?
Ans. The convention-based routing is complex to support certain URI patterns that are common in RESTful APIs. But by using attribute routing you can define these URI patterns very easily.
For example, resources often contain child resources like Clients have orders, movies have actors, books have authors and so on. It’s natural to create URIs that reflects these relations like as: /clients/1/orders
This type of URI is difficult to create using convention-based routing. Although it can be done, the results don’t scale well if you have many controllers or resource types.
With attribute routing, it’s pretty much easy to define a route for this URI. You simply add an attribute to the controller action as:



[Route("clients/{clientId}/orders")]
   public IEnumerable<Order> GetOrdersByClient(int clientId) 
     { 
      //TO DO 
     }

Q19. How to enable Attribute Routing in ASP.NET MVC?
Ans. Enabling attribute routing in your ASP.NET MVC5 application is simple, just add a call to routes.MapMvcAttributeRoutes() method with in RegisterRoutes() method of RouteConfig.cs file.


public class RouteConfig 
   { 
     public static void RegisterRoutes(RouteCollection routes)
        { routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
           //enabling attribute routing 
             routes.MapMvcAttributeRoutes(); 
         } 
   }
You can also combine attribute routing with convention-based routing.

public class RouteConfig 
     { 
           public static void RegisterRoutes(RouteCollection routes) 
             {
               routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
                 //enabling attribute routing 
                   routes.MapMvcAttributeRoutes();
                  //convention-based routing
                 routes.MapRoute(
                  name: "Default", 
                 url: "{controller}/{action}/{id}", 
                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
            }
}

Q20. How to define Attribute Routing for Area in ASP.NET MVC?
Ans. You can also define attribute routing for a controller that belongs to an area by using the RouteArea attribute. When you define attribute routing for all controllers with in an area, you can safely remove the AreaRegistration class for that area.


[RouteArea("Admin")] 
[RoutePrefix("menu")] 
[Route("{action}")]
public class MenuController : Controller 
  {
    // route: /admin/menu/login 
       public ActionResult Login()
      {
           return View();
      }
         // route: /admin/menu/products
        [Route("products")]
         public ActionResult GetProducts()
        {
               return View();

         }     
         [Route("~/categories")] 
        public ActionResult Categories() 
        { 
          return View(); 
        }

      
}


No comments :

Post a Comment