Thursday, January 2, 2014

Top 20 ASP.Net MVC Interview Questions and Answers

1. What is MVC?
MVC is a framework pattern that splits an application’s implementation logic into three component roles: models, views, and controllers.
Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.
View: The user interface that renders the Model into a form of interaction.
Controller: Handles a request from a View and updates the Model that results in a change of the Model's state.

2. ASP.Net MVC Life cycle


a. Routing: For a request, Asp.net Routing is first pass through the UrlRoutingModule is an HTTP module which parses the request and performs route selection. The UrlRoutingModule object selects the route object that matches the current request URL against the registered URL patterns in the Route Table. An application has only one Route Table and this is setup in the Global.asax file of the application.
 public static void RegisterRoutes(RouteCollection routes)  
 {  
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
   routes.MapRoute(  
     name: "Default", // Route name  
     url: "{controller}/{action}/{id}", // Url with parameter  
     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // parameter as default  
     constraints: new { id = @"\d+"} // constraint for parameter  
   );  
 }  
b. MvcHandler: The MvcHandler is responsible for handling the request and producing the response for specific content types. MVC handler implements IHttpHandler interface and further process the request by using ProcessRequest method as shown below:
 protected internal virtual void ProcessRequest(HttpContextBase httpContext)  
 {  
   SecurityUtil.ProcessInApplicationTrust(delegate  
   {  
     IController controller;  
     IControllerFactory factory;  
     this.ProcessRequestInit(httpContext, out controller, out factory);  
     try  
     {  
       controller.Execute(this.RequestContext);  
     }  
     finally  
     {  
       factory.ReleaseController(controller);  
     }  
   });  
 }  
c. Controller: MVC controllers are responsible for responding to requests made against an ASP.NET MVC website. The MvcHandler uses IControllerFactory to get IController instance. IControllerFactory could be the default or a custom factory initialized at the Application_Start event, as below:
 protected void Application_Start()  
 {  
   AreaRegistration.RegisterAllAreas();  
   RegisterRoutes(RouteTable.Routes);  
   ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());  
 }  
d. Action Execution: After controller instantiated, Controller's ActionInvoker determines which specific action to invoke on the controller. Action to be executed by default method which have the same name as the action and ActionMethodSelectorAttribute helps if more than one method found, to choose the correct action.
f. View Result: This prepares the appropriate response data then executes the result by returning a result type which can be a ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.
e. View Engine: The is responsible for creating HTML by selecting the appropriate View Engine to render the View Result. It is handled by IViewEngine interface of the view engine. By default Asp.Net MVC uses WebForm and Razor view engines. You can also register your own custom view engine to your Asp.Net MVC application as shown below:
 protected void Application_Start()   
 {   
  //Remove All View Engine including Webform and Razor  
  ViewEngines.Engines.Clear();  
  //Register Your Custom View Engine  
  ViewEngines.Engines.Add(new CustomViewEngine());  
  //Other code is removed for clarity  
 }   

g. View: It renders a view in the browser by using an IView instance that is returned by an IViewEngine object. 

3. Difference between Asp.Net MVC and Web Forms 
Asp.Net Web Forms
Asp.Net MVC
Web Form follows a traditional event driven development model.
MVC is a lightweight and follow MVC (Model, View, Controller) pattern based development model.
Web Form has server controls.
MVC has html helpers.
Web Form has state management (like as view state, session) techniques.
MVC has no default state management techniques.
Web Form has file-based URLs means file name exist in the URLs must have its physically existence.
Asp.Net MVC has route-based URLs means URLs are divided into controllers and actions and moreover it is based on controller not on physical file.
Web Form follows Web Forms Syntax
MVC follow customizable syntax (Razor as default)
In Web Form, Web Forms(ASPX) i.e. views are tightly coupled to Code behind(ASPX.CS) i.e. logic.
In MVC, Views and logic are kept separately.
Web Form has Master Pages for consistent look and feels.
MVC has Layouts for consistent look and feels.
Web Form has User Controls for code re-usability. 
MVC has Partial Views for code re-usability.

4. What are the new features of MVC2?
ASP.NET MVC 2 was released in March 2010. Its main features are:
Attribute-based model validation on both client and server
Strongly typed HTML helpers
Improved Visual Studio tooling
Support for partitioning large applications into areas
Asynchronous controllers support
Support for rendering subsections of a page/site using Html.RenderAction

5. What are the new features of MVC3?
ASP.NET MVC 3 shipped just 10 months after MVC 2 in Jan 2011.
The Razor view engine
Support for .NET 4 Data Annotations
Greater control and flexibility with support for dependency resolution and global action filters.

6. What are the new features of MVC4?
ASP.NET Web API Controllers
Enhancements to default project templates
Mobile project template using jQuery Mobile
Task support for Asynchronous Controllers
Bundling and minification

7. What is ViewStart?
The _ViewStart.cshtml page can be used to remove this redundancy. The code within this file is executed before the code in any view placed in the same directory. This file is also recursively applied to any view within a subdirectory. When we create a default ASP.NET MVC project, we find there is already a _ViewStart .cshtml file in the Views directory. It specifies a default layout:
 @{  
      Layout = "~/Views/Shared/_Layout.cshtml";  
 }  
Because this code runs before any view, a view can override the Layout property and choose a different one.

8. Difference between ViewData vs ViewBag vs TempData objects
S.No
ViewData
ViewBag
TempData
1
This is a dictionary object that is derived from ViewDataDictionary class
It is a dynamic property that takes advantage of the new dynamic features in C# 4.0
It is a dictionary object that is derived from TempDataDictionary class and stored in short lives session. RedirectResult and RedirectToRouteResult always calls TempData.Keep() to retain items in TempData.
2
It is used to pass data from controller to corresponding view
It is also used to pass data from controller to corresponding view
It is used to pass data from a controller to an another controller or action to action while redirection
3
If redirection occurs then it’s value becomes null.
If redirection occurs then it’s value becomes null.
It’s required typecasting for complex data type and check for null values to avoid error.
4
Typecasting is required for complex data type
Typecasting is not required.
Typecasting is required for complex data type

9. Data Annotations (System.ComponentModel.DataAnnotations)
Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users. Add jquery.validate.min.js and jquery.validate.unobtrusive.min.js references to page.
DataType: Specify the datatype of a property.
 [DataType(DataType.EmailAddress)]  
DisplayName: specify the display name for a property.
 [Display(Name = "Email address")]  
DisplayFormat: specify the display format for a property like different format for Date proerty.
 [DisplayFormat(DataFormatString = "{0:###-###-####}")] // PhoneNo  
Required: Specify a property as required. 
 [Required(ErrorMessage = "Name is required")]  
ReqularExpression: validate the value of a property by specified regular expression pattern.
 [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}",   
                    ErrorMessage = "Please enter correct email")]  
Range: validate the value of a property with in a specified range of values.
 [Range(3000, 10000,  
       ErrorMessage = "Salary must be between 3000 and 10000")]  
StringLength: specify min and max length for a string property. 
 [StringLength(300)] // Address  
MaxLength: specify max length for a string property. 
 [MaxLength(50)] // Email  
Bind: specify fields to include or exclude when adding parameter or form values to model properties.
 [Bind(Exclude = "EmpId")]  
ScaffoldColumn: specify fields for hiding from editor forms.
 [ScaffoldColumn(false)]  
 
10. Filters in MVC
MVC provides a very clean way of injecting the pre-processing and post-processing logic for actions and controllers.
a. Authorization filter
This filter provides authentication and authorization logic. It will be executed before the action gets executed.
 public class CustomAuthorizationAttribute : FilterAttribute, IAuthorizationFilter  
 {  
   void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)  
   {  
      filterContext.Controller.ViewBag.OnAuthorization = "IAuthorizationFilter.OnAuthorization filter called";  
   }  
 }  
b. Action filter
 public class CustomActionAttribute : FilterAttribute, IActionFilter  
 {  
   //before action runs  
   void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)  
   {  
   }  
   //after action runs  
   void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)  
   {  
   }  
 }  
c. Result filter
 public class CustomResultAttribute : FilterAttribute, IResultFilter  
 {  
   void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)  
   {  
   }  
   void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)  
   {  
   }  
 }  
d. Exception filter
This filter will be invoked whenever a controller or action of the controller throws an exception.
 public class CustomExceptionAttribute : FilterAttribute, IExceptionFilter  
 {      
   void IExceptionFilter.OnException(ExceptionContext filterContext)  
   {  
     filterContext.Controller.ViewBag.OnException = "IExceptionFilter.OnException filter called";  
   }  
 }  
Implementation of filters on controller,
 public class HomeController : Controller  
 {    
   [CustomAuthorization]  
   [CustomAction]  
   [CustomResultAttribute]  
   [CustomExceptionAttribute]  
   public ActionResult Index()  
   {  
     //throw new Exception("Dummy Exception");  
     ViewBag.Message = "Index Action of Home controller is being called.";  
     return View();  
   }  
 }  
11. How to prevent public controller method from being implicitly bound to action name?
 [NonAction] //to prevent  
 public ActionResult ContactUs()  
 {  
 }  
12. Return types of an action
An action method is used to return an instance of any class which is derived from ActionResult class.
ViewResult: It is used to return a view page from an action method. return View([model])
PartialViewResult: It is used to send a section of a view to be rendered inside another view. return PartialView(“viewname”, [model]) 
JavaScriptResult: It is used to return JavaScript code which will be executed in the user’s browser. return JavaScript(“’aler(‘Hello!’);”)//this wont work without serializer 
RedirectResult: Based on a URL, It is used to redirect to another controller and action method. return Redirect(“http://www.google.com”) or RedirectToAction
ContentResult: It is an HTTP content type may be of text/plain. It is used to return a custom content type as a result of the action method. return Content(“Hello“)
JsonResult: It is used to return a message which is formatted as JSON. Return Json(jsonObject)
FileResult: It is used to send binary output as the response. return File(filePath)
EmptyResult: It returns nothing as the result. return Empty() 

13. Explain about default route, {resource}.axd/{*pathInfo}
With the help of this default route {resource}.axd/{*pathInfo}, you can prevent requests for the web resources files such as WebResource.axd or ScriptResource.axd from being passed to a controller.

14. What is strongly typed view in MVC?
Strongly type view is used for rendering specific type of model object.

15. How to avoid Cross Site Request Forgery (CSRF) in ASP.NET MVC?
Cross Site Request Forgery (CSRF) is a type of attack on the web application or on the website where a malicious user can insert or update data on behalf of the logged in user of the application by giving him a link that is not of the victim website but attackers own website.
Add [ValidateAntiForgeryTocker] attribute in the Controller Action method which is executing when the form data is being submitted. 
Add @Html.AntiForgeryTocker() element in the HTML form.

16. How do you handle variable number of segments in a route definition?
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter. controller/{action}/{*parametervalues}

17. Give 2 examples for scenarios when routing is not applied?
A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true.
Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.

18. What does mean by Dependency Injection (DI)?
Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.
The advantages of using Dependency Injection pattern and Inversion of Control are the following:
                Reduces class coupling
Increases code reusing
Improves code maintainability
Improves application testing

19. What is Web API? Why Web API needed, If you have already RESTful services using WCF?
     Web API is a new framework for consuming & building HTTP Services.
     Web API supports wide range of clients including different browsers and mobile devices.
     It is very good platform for developing RESTful services since it talk’s about HTTP.
     we can still develop the RESTful services with WCF, but there are two main reasons that prompt users to use Web API instead of RESTful services,
     a. ASP.NET Web API is included in ASP.NET MVC which obviously increases TDD (Test Data Driven) approach in the development of RESTful services.
     b. For developing RESTful services in WCF you still needs lot of config settings, URI templates, contract’s & endpoints which developing RESTful services using web API is simple.

20. What are the difference between asynchronous controller implementation b/w ASP.NET MVC 3 & ASP.NET MVC 4? 
     There is a difference is on implementation mechanism between ASP.NET MVC 3 and ASP.NET MVC 4. 
     In ASP.NET MVC 3, to implement async controller or methods we need to derive controller from AsyncController rather than from normal plain Controller class. We need to create 2 action methods rather than one. First with suffix ’Async’ keyword & second with ‘Completed’ suffix. 
     In ASP.NET MVC 4 you need not to declare 2 action method. One can serve, MVC 4 using .Net Framework 4.5 support for asynchronous communication.

2 comments: