MVC Interview Question and Answers with Example - Part 1


Below is top 100 MVC interview question and answers with examples for freshers and intermediate developers.

What is MVC?

MVC stands for Model View Controller. It is an architectural pattern to develop enterprise application. It is not a Microsoft technology, whether it is a common design pattern that is used to create web application. It is used to create structure user-oriented application. MVC is most similar to MVVM [Model View View-Model] but not completely.

What is ASP.NET MVC?

ASP.NET MVC is a framework that supports MVC Design Pattern to develop different kinds of application. It is Microsoft Open Source Framework and also light weight to other framework. It provides us many features such as Routing, Unit Test Capability, Bundling and Minification, Separation of the code, etc. Loose coupling is the main concern to use ASP.NET MVC.

  • Model is responsible for maintaining application data and business logic.
  • View is a user interface of the application, which displays the data.
  • Controller handles user's requests and renders appropriate View with Model data.

What is an Architectural Pattern?

An architectural pattern is a general, reusable solution to a commonly occurring problem in software architecture within a given context. Architectural patterns are similar to software design pattern but have a broader scope. 10 common architectural patterns are:

  • Layered pattern
  • Client-server pattern
  • Master-slave pattern
  • Pipe-filter pattern
  • Broker pattern
  • Peer-to-peer pattern
  • Event-bus pattern
  • Model-view-controller pattern
  • Blackboard pattern
  • Interpreter pattern

What is the difference between architecture pattern and design pattern?

Differences: Architecture is strategic, while Design is tactical. Design Patterns are well known patterns for solving technical problems in a way that has proven itself many times. However architecture patterns are well known patterns for solving software application architecture problems. Architecture comprises the frameworks, tools, programming paradigms, component-based software engineering standards, design principles.
Similarities: Both architectural and design pattern seems to implement set of frameworks and techniques to enforce code reusability and solve common known software problem

What are advantages of ASP.NET MVC?

Below are the advantages of ASP.NET MVC over web forms.
Separation of concern: MVC design pattern divides the ASP.NET MVC application into three main aspects Model, View and Controller which make it easier to manage the application complexity.
TDD: The MVC framework brings better support to test-driven development.
Extensible and pluggable: MVC framework components were designed to be pluggable and extensible and therefore can be replaced or customized easier then Web Forms.
Full control over application behaviour: MVC framework doesn’t use View State or server based forms like Web Forms. This gives the application developer more control over the behaviors of the application and also reduces the bandwidth of requests to the server.
ASP.NET features are supported: MVC framework is built on top of ASP.NET and therefore can use most of the features that ASP.NET include such as the providers architecture, authentication and authorization scenarios, membership and roles, caching, session and more.
URL routing mechanism: MVC framework supports a powerful URL routing mechanism that helps to build a more comprehensible and searchable URLs in your application. This mechanism helps to the application to be more addressable from the eyes of search engines and clients and can help in search engine optimization.

What is difference between ASP.NET WebForm and ASP.NET MVC?

ASP.NET Web FormsASP.NET MVC
ASP.NET Web Form follows a traditional event driven development model. ASP.NET MVC is a lightweight and follow MVC (Model, View, and Controller) pattern based development model.
ASP.NET Web Form has server controls. ASP.NET MVC has html helpers.
ASP.NET Web Form has state management (like as view state, session) techniques. ASP.NET MVC has no automatic state management techniques.
ASP.NET 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.
ASP.NET Web Form follows WebForm Syntax. ASP.NET MVC follow customizable syntax (Razor as default).
In ASP.NET Web Form, Web Forms (ASPX) i.e. views are tightly coupled to Code behind (ASPX.CS) i.e. logic. In ASP.NET MVC, Views and logic are kept separately.
ASP.NET Web Form has Master Pages for consistent look and feels. ASP.NET MVC has Layouts for consistent look and feels.
ASP.NET Web Form has User Controls for code re-usability. ASP.NET MVC has Partial Views for code re-usability.
ASP.NET Web Form has built-in data controls and best for rapid development with powerful data access. ASP.NET MVC is lightweight, provide full control over mark-up and support many features that allow fast & agile development. Hence it is best for developing interactive web application with latest web standards.
ASP.NET Web Form is not Open Source. ASP.NET Web MVC is an Open Source.

Explain MVC application life cycle?

Steps involved in MVC application life cycle are show below.
Fill route: MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.
Fetch route: Depending on the URL sent "UrlRoutingModule" searches the route table to create "RouteData" object which has the details of which controller and action to invoke.
Request context created: The "RouteData" object is used to create the "RequestContext" object.
Controller instance created: This request object is sent to "MvcHandler" instance to create the controller class instance. Once the controller class object is created it calls the "Execute" method of the controller class.
Creating Response object: This phase has two steps executing the action and finally sending the response as a result to the view.

What is Model?

  • Model represents domain specific data and business logic in MVC architecture.
  • It maintains the data of the application.
  • Model objects retrieve and store model state in the persistance store like a database.
  • Model class holds data in public properties.
  • All the Model classes reside in the Model folder in MVC folder structure.

What is View?

  • View is a User Interface which displays data and handles user interaction.
  • Views folder contains separate folder for each controller.
  • ASP.NET MVC supports Razor view engine in addition to traditional .aspx engine.

What is Controller?

  • A Controller handles incomming URL requests. MVC routing sends request to appropriate controller and action method based on URL and configured Routes.
  • All the public methods in the Controlle class are called Action methods.
  • A Controller class must be derived from System.Web.Mvc.Controller class.
  • A Controller class name must end with "Controller".
  • New controller can be created using different scaffolding templates. You can create custom scaffolding template also.

What is action method?

  • All the public methods in the Controller class are called Action methods.
  • Action method has following restrictions.
    • Action method must be public. It cannot be private or protected.
    • Action method cannot be overloaded.
    • Action method cannot be a static method.
  • ActionResult is a base class of all the result type which returns from Action method.
  • Base Controller class contains methods that returns appropriate result type e.g. View(), Content(), File(), JavaScript() etc.
  • Action method can include Nullable type parameters.

What are the different return types of Action Method?

Result ClassBase Controller MethodDescription
ViewResult View() Represents HTML and markup.
EmptyResult Represents No response.
FileContentResult, FilePathResult, FileStreamResult File() Represents the content of a file
JavaScriptResult JavaScript() Represent a JavaScript script.
JsonResult Json() Represent JSON that can be used in AJAX.
RedirectResult Redirect() Represents a redirection to a new URL.
RedirectToRouteResult RedirectToRoute() Represent another action of same or other controller.
PartialViewResult PartialView() Returns HTML
HttpUnauthorizedResult Returns HTTP 403 status

What is routing in ASP.NET MVC?

ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match

How routing works?

When the application starts up, ASP.NET MVC discovers all of the application's controllers by searching through the available assemblies for a class that implements the System.Web.Mvc. IController interface or derived from a class that implements this interface and whose class names end with the suffix Controller. When the routing framework uses this list to determine which controller it has access to, it chops off the Controller suffix from the entire controller class names.

How to define a route in ASP.NET MVC?

You can define a route in ASP.NET MVC as given below.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        name: "Default", // Route name
        url: "{controller}/{action}/{id}", // Route Pattern
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Default values for above defined parameters
    );
}
protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
}

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.

Request URLParameters
http://example.com/ controller=Home, action=Index, id=none, Since default value of controller and action are Home and Index respectively.
http://example.com/Admin controller=Admin, action=Index, id=none, Since default value of action is Index
http://example.com/Admin/Product controller=Admin, action=Product, id=none
http://example.com/Admin/Product/1 controller=Admin, action=Product, id=1
http://example.com/Admin/Product/SubAdmin/1 No Match Found
http://example.com/Admin/Product/SubAdmin/Add/1 No Match Found

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.

What is Attribute Routing and how to define it?

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.

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/Contact 
    public ActionResult Contact()
    {
    return View();
    }
}

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()
    {
       return View();
    }

    [Route("users/about")] //route" /users/about
   public ActionResult About()
    {
       return View();
    }

   //route: /Home/Contact
   public ActionResult Contact()
    {
       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-based routing will not be the part of attribute routing. In this way they can’t be access from outside as a URI.

When to use Attribute Routing?

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) 
{ 
}

How to enable Attribute Routing in ASP.NET MVC?

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();
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

How to define Attribute Routing for Area in ASP.NET MVC?

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
   [Route("~/categories")]
   public ActionResult Categories()
    {
      return View();
    }
}

What is Route Constraints in ASP.NET MVC?

Route constraints is way to put some validation around the defined route. Suppose we have defined the following route in our application and you want to restrict the incoming request url with numeric id only.Now let's see how to do it with the help of regular expression.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        name: "Default", // Route name
        url: "{controller}/{action}/{id}", // Route pattern
        // Default values for parameters
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        constraints:new  { id = @"\d+" } //Restriction for id
    );
}

Now for this route, routing engine will consider only those URLs which have only numeric id like as http://example.com/Admin/Product/1 else it will considers that url is not matched with this route.

How route table is created in ASP.NET MVC?

When an MVC application first starts, the Application_Start() method in global.asax is called. This method calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table for MVC application.

What are important namespaces in ASP.NET MVC?

There are some important namespaces as given below:
System.Web.Mvc: This namespace contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders.
System.Web.Mvc.Ajax: This namespace contains classes that supports Ajax scripting in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings as well.
System.Web.Mvc.Html: This namespace contains classes that help render HTML controls in an MVC application. This namespace includes classes that support forms, input controls, links, partial views, and validation.

What are the new features of MVC 5?

Some of the features included in MVC5 are:

  • Scaffolding
  • ASP.NET Identity
  • One ASP.NET
  • Bootstrap
  • Attribute Routing
  • Filter Overrides

What is MVC 6?

In MVC 6 ,the three frameworks,WebAPI ,MVC and SingnalR are merged into a single framework. Also in MVC dependency on System.Web is removed.

What is ASP.NET Core?

ASP.NET Core is a new version of ASP.NET.It is more than just another version of ASP.NET. It is rewritten for web and cloud applications. It has number of useful features such as:
Cross platform: Supports all the major OS such as Linux,Windows,Mac.
Open source: ASP.NET Core has huge community of developers who contribute to add new features frequently
Modular and Lightweight: Unlike ASP.NET ,ASP.Core is consumed using Nuget packages.You only need to add the nuget packages you require for a specific functionality.

What are action selectors?

MVC framework routing engine uses Action Selectors attributes to determine which action method to invoke.
Three action selectors attributes are available in MVC 5

  • ActionName
  • NonAction
  • ActionVerbs
ActionName attribute is used to specify different name of action than method name.
NonAction attribute marks the public method of controller class as non-action method. It cannot be invoked.

What is ActionVerbs?

  • ActionVerbs are another Action Selectors which selects an action method based on request methods e.g POST, GET, PUT etc.
  • Multiple action methods can have same name with different action verbs. Method overloading rules are applicable.
  • Multiple action verbs can be applied to a single action method using AcceptVerbs attribute.

What is View Engine?

A View Engine is a MVC subsystem which has its own markup syntax. It is responsible for converting server-side template into HTML markup and rendering it to the browser. Initially, ASP.NET MVC ships with one view engine, web forms (ASPX) and from ASP.NET MVC3 a new view engine, Razor is introduced. With ASP.NET MVC, you can also use other view engines like Spark, NHaml etc.

How View Engine works?

Each view engine has following three main components:
ViewEngine class: This class implements the IViewEngine interface and responsible for locating view templates.
View class: This class implements the IView interface and responsible for combining the template with data from the current context and convert it to output HTML markup.
Template parsing engine: This parses the template and compiles the view into executable code.

What is Razor View Engine?

Razor Engine is an advanced view engine that was introduced with MVC3. This is not a new language but it is a new markup syntax. Razor has new and advance syntax that are compact, expressive and reduces typing. Razor syntax are easy to learn and much clean than Web Form syntax. Razor uses @ symbol to write markup as:
@Html.ActionLink("SignUp", "SignUp")

How to make Custom View Engine?

ASP.NET MVC is an open source and highly extensible framework. You can create your own View engine by Implementing IViewEngine interface or by inheriting VirtualPathProviderViewEngine abstract class.

public class CustomViewEngine : VirtualPathProviderViewEngine
{
    public CustomViewEngine()
    {
        // Define the location of the View and Partial View 
        this.ViewLocationFormats = new string[] { 
        "~/Views/{1}/{0}.html", "~/Views/Shared/{0}.html"
        };
        this.PartialViewLocationFormats = new string[] { 
        "~/Views/{1}/{0}.html", "~/Views/Shared/{0}.html"
        };
    }

    protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
    {
        var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath);
        return new CustomView(physicalpath);
    }

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath);
        return new CustomView(physicalpath);
    }
}

public class CustomView : IView
{
    private string _viewPhysicalPath;
    public CustomView(string ViewPhysicalPath)
    {
        _viewPhysicalPath = ViewPhysicalPath;
    }
    public void Render(ViewContext viewContext, System.IO.TextWriter writer)
    {
        //Load File 
        string rawcontents = File.ReadAllText(_viewPhysicalPath); //Perform Replacements
        string parsedcontents = Parse(rawcontents, viewContext.ViewData);
        writer.Write(parsedcontents);
    }
    public string Parse(string contents, ViewDataDictionary viewdata)
    {
        return Regex.Replace(contents, "\\{(.+)\\}", m => GetMatch(m, viewdata));
    }
    public virtual string GetMatch(Match m, ViewDataDictionary viewdata)
    {
        if (m.Success)
        {
            string key = m.Result("$1"); if (viewdata.ContainsKey(key))
            {
                return viewdata[key].ToString();
            }
        }
        return string.Empty;
    }
}

How to register Custom View Engine in ASP.NET MVC?

To use your custom View Engine, you need to register it by using global.asax.cs file Application_Start() method, so that the framework will use your custom View Engine instead of the default one.

protected void Application_Start() 
{
    // Register Custom View Engine
    ViewEngines.Engines.Add(new CustomViewEngine());
}

Can you remove default View Engine in ASP.NET MVC?

Yes, you can remove default view engines (Razor and WebForm) provided by ASP.NET MVC.

protected void Application_Start() 
{
    // Remove All View Engine including Webform and Razor
    ViewEngines.Engines.Clear();
}

What is difference between Razor and WebForm engine?

Razor View EngineWebform View Engine
Razor Engine is an advanced view engine that was introduced with MVC3. This is not a new language but it is a new markup syntax. Web Form Engine is the default view engine for the Asp.net MVC that is included with Asp.net MVC from the beginning.
Razor Engine is an advanced view engine that was introduced with MVC3. This is not a new language but it is a new markup syntax. Web Form Engine is the default view engine for the Asp.net MVC that is included with Asp.net MVC from the beginning.
The namespace for Razor Engine is System.Web.Razor. The namespace for Webform Engine is System.Web.Mvc.WebFormViewEngine.
The file extensions used with Razor Engine are different from Web Form Engine. It has .cshtml (Razor with C#) or .vbhtml (Razor with VB) extension for views, partial views, editor templates and for layout pages. The file extensions used with Web Form Engine are also like Asp.net Web Forms. It has .aspx extension for views, .ascx extension for partial views & editor templates and .master extension for layout/master pages.
Razor has new and advance syntax that are compact, expressive and reduces typing. Web Form Engine has the same syntax like Asp.net Web Forms uses for .aspx pages.
Razor syntax are easy to learn and much clean than Web Form syntax. Razor uses @ symbol to make the code like as: @Html.ActionLink("SignUp", "SignUp") Web Form syntax are borrowed from Asp.net Web Forms syntax that are mixed with html and sometimes make a view messy. Webform uses <% and %> delimiters to make the code like as: <%: Html.ActionLink("SignUp", "SignUp") %>
By default, Razor Engine prevents XSS attacks (Cross-Site Scripting Attacks) means it encodes the script or html tags like <,> before rendering to view. Web Form Engine does not prevent XSS attacks means any script saved in the database will be fired while rendering the page.
Razor Engine is little bit slow as compared to Webform Engine. Web Form Engine is faster than Razor Engine.
Razor Engine, doesn't support design mode in visual studio means you cannot see your page look and feel. Web Form engine support design mode in visual studio means you can see your page look and feel without running the application.
Razor Engine support TDD (Test Driven Development) since it is not depend on System.Web.UI.Page class. Web Form Engine doesn't support TDD (Test Driven Development) since it depend on System.Web.UI.Page class which makes the testing complex.

Page 1 of 3