Important ASP.Net MVC interview questions and answers

In this blog, I have collected ASP.Net MVC interview questions and answers. For an ASP.Net developer, MVC is very important for interviews in any MNCs.
Whether you are a fresher or have .Net MVC development experience, the .Net MVC interview questions given below will prove to be very beneficial for you.

Table of Contents

Top ASP.Net MVC Interview questions and their answers

1. What is MVC?

The first question for a fresher may be What is MVC?
MVC – A commonly used software design pattern. MVC is a new architectural pattern introduced by Microsoft. MVC gives you cleaner and more maintainable code which makes developer life easy.

MVC consists of a Model, View, and Controller.

Model –

Model is the domain-specific classes in MVC architecture. It represents the data that users work with.

View-

A view in MVC is the user interface. It is similar to ASPX pages, but View in MVC may consist of Razor View Engine. MVC views are stored in the Views folder.

Controller –

A controller in MVC is responsible for handling incoming requests. Controller class derived from System.Web.Mvc.Controller class.

Controllers receive the request and call the model, create the object of the model, call the view and pass the data to the view to display the result.

Know more about ASP.Net MVC

2. Benefits of using ASP.Net MVC

MVC is not the only software design pattern, there are numerous other patterns. Then Why to choose MVC?

In ASP.Net, everything is ASPx and .cs file where three-layer architecture can be implemented.

MVC has 3 sections Model, View, and Controller.

Here we can divide MVC in three-layer architecture as below.

A controller is equal to the Code behind the logic.

The view is equivalent to ASPX/HTML page.

The model is the middle layer.

In MVC, the first hit comes to the controller. Depending on the action, the Controller creates the object of the model.

3. Explain the MVC application life cycle

This is another important MVC interview question.

The life cycle in the MVC application always starts with Routing. All Routing must be associated with a Controller and Action method.

In ASP.Net, ASPX pages implement IHTTPHandler interface, this interface has a method called ProcessRequest().

But in MVC there are no physical pages. All requests are mapped to a Controller class with their Action method.

So if a controller class is DefaultController and the Action method is Index

then the request URL pattern will be  http://localhost/Default/Index

A single controller class can handle multiple requests.

Simply understand the MVC lifecycle below –

App Start => Routing => Initialize and Execute Controller => Locate and Execute Action => Render View

4. What are Filters in MVC

Another important MVC interview question is MVC filter.

MVC offers 4 types of filters.

1. Authorization Filters – Implements IAuthorizationFilter interface
Executes before an action method to check the authenticity of a user which is going to execute the specific action method.

2. Action Filters – Implements IActionFilter interface
IActionFilter.OnActionExecuting method executes before an action method gets executed and once the action method is executed IActionFilter.OnActionExecuted method gets invoked.

3. Result Filters – Implements IResultFilter interface
Before executing the result IResultFilter.OnResultExecuting methods called and after executing the result, IResultFilter.OnResultExecuted method gets invoked.
4. Exception Filters – Implements IExceptionFilter interface

Executes when an action throws an exception in between any stage of execution.

5. Explain Routing in MVC

It is one of the most asked questions in an ASP.Net MVC interview.

The MVC route is the most important section in the MVC pattern. Routing in MVC matches incoming requests to a controller action. Routing is the way to map the action of a controller. So, basically, routing defines which action method of which controller will be called for a defined URL pattern. ASP.Net MVC supports routing by default. Basically, MVC routes define the URL pattern. Read more about MVC Routing here.

6. Differences between Temp Data vs View Bag

This is also a more frequently asked question in the .Net MVC interview.

What is ViewBag?

ViewBag uses dynamic type.ViewBag was introduced in ASP.Net MVC 3.0;
A sample code to assign the value to ViewBag.

public ActionResult DisplayProductName()
        {
            var product = new Products { ProductName = “Laptop” };
            ViewBag.Product = product;
            return View();
        }

Access ViewBag in View –

@ViewBag.Product.ProductName

What is TempData?

TempData is useful if you want to transfer data from one action to another action within the same controller or the different controller.

TempData in MVC is used to store temporary data for a short period of time.
What is the duration of a short period of time?
Here, a short period of time means a subsequent request. Data stored in TempData will be lost after the completion of the subsequent request.

Once you request – localhost/Test/Book then it will redirect to localhost/Test/DisplayBook and display the result – “MVC Ebook”.

Read more – viewbag vs viewdata vs tempdata

public class TestController : Controller
    {
        public ActionResult Book()
        {
            TempData[“product”] = “MVC Ebook”;
            return RedirectToAction(“DisplayBook”);
        }
        public string DisplayBook()
        {
            return TempData[“product”].ToString();
        }
    }

 

7. What is a Partial View in ASP.Net MVC?

Partial View provides re-usability features. A partial View is an effective way to break large Views into smaller sections. It is similar to UserControl in the traditional ASP.Net application. PartialView is a child view rendered within a normal View page.
Partial View can be used within the Layout page as well as in normal View pages.

Partial View can be used like this –

  @Html.Partial(“_HeaderSectionPartial”)

8. Differences between View and Partial View

In the previous question, we have seen a Partial View.  A partial View is used to break down the larger View.
For eg – We can create a website header as a Partial View, we can create Footer as a different Partial View and render these Partial Views on the View page using @Html.Partial(“_PartialViewName”)

The view is the user interface in the MVC application. It takes data from the Model and displays it for the user.
A view contains HTML and Razor View code.

9. HTML Helpers in MVC

This is one another important MVC interview questions.

HTML Helper methods are predefined methods in ASP.Net MVC to work with HTML forms.
HTML helper methods generate specific HTML tags on the browser.

For eg – HTML helper @Html.TextBoxFor(model=>model.ProductName) output is <input type=”text” name=”ProductName”>

Note – ProductName is a property in our Model.

Similarly for TextBoxArea, @Html.TextBoxAreaFor(model=>model.ProductDescription)

@Html.BeginForm() is rendered as <form> </form>

For Textbox, you may either use @Html.TextBox or @Html.TextBoxFor.
@Html.TextBoxFor is strongly typed HTMLHelper

10. MVC4 vs MVC5

Differences between MVC versions –

Version
Release Year
Features
MVC 1.0
2009
MVC pattern with ASPX engine
HTML Helpers
MVC 2.0
2010
MVC 3.0
2011
Razor Engine
Global Filters
MVC 4.0
2012
Bundling and Minifications
MVC 5.0
2013
ASP.Net Web API 2
2016
Open Source
Cross Platform
Cloud Compatibility
2017

11. What is Scaffolding in ASP.Net MVC?

Scaffolding is the process of automatic code generation. This is the easiest way to create an MVC application.

Scaffolding comes pre-installed from Visual Studio 2013 onwards.

12. What is Bundling and Minification in MVC?

Bundling and Minification are used to reduce the number of requests and to increase the performance of a web page. These are the way to optimize web applications.

A website contains multiple Script and Stylesheet files to provide better UI to its customers. Using multiple script and style files may degrade the website’s performance.

When you create an MVC application, you may find Bundleconfig.cs file in the App_Start folder.
This BundleConfig.cs file contains a method RegisterBundles which accepts a parameter of type BundleCollection.

BundleCollection class comes under the namespace System.Web.Optimization

13. How to implement form validation in ASP.Net MVC?

Form Validation in an MVC application can be done either by JQuery or Data Annotation.
Here We will discuss Data Annotation –

A few Data Annotation attributes are –

  • Required
  • DisplayName
  • Range
  • StringLength
  • MaxLength
  • MinLength

All the above-mentioned Data Annotation attribute comes under –  System.ComponentModel.DataAnnotations namespace.

Know more about Data Annotation.

14. Html.Partial vs Html.RenderPartial

Html.Partial returns a string, Html.RenderPartial returns nothing i.e. Void
Syntax Differences
@Html.Partial(“_PartialViewName”);
@{Html.RenderPartial(“_PartialViewName”)}

Html.RenderPartial() loads faster than Html.Partial as Html.RenderPartial writes HTML directly in the response stream.

15. What is {resource}.axd/{*pathInfo} in Routeconfig.cs

{resource}.axd/{*pathInfo} is a pattern in RouteConfig file which restricts web resource files requests such as WebResource.axd, ScriptResource.axd

16. How to implement paging in MVC?

There could be multiple ways to manage pagination in the MVC application.
But Html.PagedListPager is the simple one to manage pagination.
Html.PagedListPager is the function of HtmlHelper class.

Also for the proper functioning of pagination with Html.PagedListPager, you must reference jquery.unobtrusive-ajax.js file on your page.

17. What is PagedList.Mvc?

PagedList.Mvc is used to implement pagination in MVC. It contains an HtmlHelper class which is having 5 methods that help to implement paging on MVC applications.

public static MvcHtmlString PagedListGoToPageForm(this System.Web.Mvc.HtmlHelper html, IPagedList list, string formAction);
 
        public static MvcHtmlString PagedListGoToPageForm(this System.Web.Mvc.HtmlHelper html, IPagedList list, string formAction, GoToFormRenderOptions options);
 
        public static MvcHtmlString PagedListGoToPageForm(this System.Web.Mvc.HtmlHelper html, IPagedList list, string formAction, string inputFieldName);
 
        public static MvcHtmlString PagedListPager(this System.Web.Mvc.HtmlHelper html, IPagedList list, Func<int, string> generatePageUrl);
 
        public static MvcHtmlString PagedListPager(this System.Web.Mvc.HtmlHelper html, IPagedList list, Func<int, string> generatePageUrl, PagedListRenderOptions options);
 

18. What is Area in ASP.Net MVC?

The Area in MVC is basically a part of the project. This means an application could have different sections such as Admin, Users or Customers, Moderator, Editor, Author, etc.
In such a condition, we can create Areas for all the sections. The area is used in large applications only.

You must register your area in the Application_Start method in the Global.asax file.

AreaRegistration.RegisterAllAreas();

Read more about  Areas in MVC

19. What are the Differences between ViewData and ViewBag?

ViewData in MVC is used to transfer data from Controller to View.
Every controller has a property called ‘ViewData’ of type ViewDataDictionary, which contains key-value pair.

It is similar to ViewData, but the difference is instead of using a string value, ViewBag uses a dynamic type.ViewBag was introduced in ASP.Net MVC 3.0.

Read more about TempData, ViewBag, and ViewData

20. What is the Unobtrusive JQuery library in MVC?

Unobtrusive is the library to manage client-side work such as Form Validation in an MVC application.
Unobtrusive allows us to implement form validation without writing a bunch of code.
The unobtrusive script file is automatically included in the MVC application in Visual Studio. You may also get this library from NuGet.

21. How to handle an exception in an MVC application?

Exception in MVC application can be handled in numerous ways –

1. Try-Catch block
2. OnException method in Controller
3. ExceptionFilters
4. HandleError attribute

Know more about Exception Handling in ASP.Net MVC

22. What is RenderSection in MVC?

RenderSection() method is optional.
RenderSection() takes the parameter as a section name and a boolean parameter which is optional.
The first parameter is of string type which is the name of the section i.e. in layout pages, renders the content of a named section.
The second parameter is of a boolean type which says – In layout pages, renders the content of a named section and specifies whether the section is required.

A RenderSection() method looks like this –

  @RenderSection(“sectioname1”, required: true)

23. Attribute Routing in ASP.Net MVC

MVC5 supports a new type of routing, this is called Attribute Routing.
In order to implement Attribute Routing, we must enable it in the RouteConfig file. See the highlighted line below.

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

routes.MapMvcAttributeRoutes() actually maps the attribute-defined routes for the application.

Know more about Attribute Routing in MVC 5

24. What is Ant-Forgery Token in ASP.Net MVC?

An anti-forgery token is used to secure the application against Cross-Site Request Forgery (CSRF).
In our MVC form page, i.e.on View just add this line –
@Html.AntiForgeryToken();

This method will create a token similar to a secret code, it keeps this value in a hidden field and also as a cookie on the user’s computer.

So whenever you request data from the server, a RequestVerificationToken is generated as shown in the below screenshot.

You may find these details by pressing F12 (developer tools) in Chrome, Firefox or any browser.

Know more about Anti Forger Token in MVC

25. What is Dependency Injection in MVC?

Dependency Injection is the most asked interview question for ASP.Net MVC developers.
Dependency Injection is a design approach, which helps to create loosely coupled code. In another way, we can say that Dependency Injection is used to remove the dependency between two classes and helps to create independent classes.

Read about Dependency Injection in C#

26. How to apply security in MVC application?

You may apply security in the MVC application by applying Authorize attribute to the Action method or Controller class.

Authorize Attribute to Action method –

        [Authorize]
        public ActionResult Test()
        {
            return View();
        }

Suppose you do not want to write Authorize attribute to all action methods. Then you can apply to add Authorize attribute to the Controller class.

In the below code, all action methods with no Authorize attribute in HomeController will be treated with Authorize attribute.
And Action method with the attribute AllowAnonymous will have anonymous access.

    [Authorize]
    public class HomeController : Controller
    {
        public ActionResult Test()
        {
            return View();
        }
        [AllowAnonymous]
        public ActionResult Test1()
        {
            return View();
        }
     }

27. What is ActionName and NonAction attribute?

ActionName and NonAction attribute in MVC is the attribute applied to an action method. These attribute helps the routing engine to execute the correct Action method and the respective View.
Read more about – ActionName and NonAction attribute

28. Html.ActionLink and Html.RouteLink

Html.ActionLink method renders a hyperlink in the browser.
Html.ActionLink accepts 3 parameters.
The first parameter is the Text of the link, which can be any string.
2nd parameter is the name of the action method.
3rd parameter is the name of the Controller.

@Html.ActionLink(“Link name”, “Index”, “Home”);
Html.RouteLink does the same thing, instead of action and controller name Html.RouteLink accepts the route name as 2nd parameter.

In the below line of code, Homestart is the name of the route in the RouteConfig.cs file.
@Html.RouteLink(“Link Text1”, “Homestart”);
Html.RouteLink can be written like this.
In the below line of code, 2nd parameter is the routeValues of the type object.
@Html.RouteLink(“Link Text12”, new { action= “index” });

29. What’s new in ASP.Net MVC4?

  • ASP.Net Web API
  • Empty Project Template
  • Support for Microsoft Azure

30. What’s new in ASP.Net MVC5?

  • ASP.Net Identity
  • One ASP.Net
  • Attribute Routing
  • Filter Overrides

31. What is a Layout in MVC?

The layout provides a common UI part of a web application for eg Header, the Footer. The concept of Layout in MVC is the same as Masterpage in ASP.Net web forms application.

We can call  @RenderBody() in the Layout page where the body content of a view page will load.
To inherit a view page with Layout we need to add the below code at the top of View.

@{
    Layout = “~/View/Shared/_Layout.cshtml”;
}

32. How to define a route for an Area in MVC?

When we create an Area in MVC a class is added in the folder which inherits AreaRegistration abstract class and contains a RegisterArea method.
public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                “Area1”,
                “AreaName/{controller}/{action}/{id}”,
                new { action = “Index”, id = UrlParameter.Optional }
            );
        }
Above MVC interview questions and answers are important for all MVC developers whether they are beginners or have multiple years of experience.

Other Interview Questions and Answers –

Important ASP.Net Interview Questions and Answers
Top Web API interview questions and answers
OOPS Interview Questions and Answers
C# Important interview questions and answers

Leave a Comment

RSS
YouTube
YouTube
Instagram