Important ASP.Net MVC interview questions and answers

Hi All, I have collected important MVC interview questions and answers based on the internet search and development experience.

1. 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 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 stored in Views folder.

Controller - 

A controller in MVC is responsible for handling the 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 view and pass the data to the view to display the result.

Know more about ASP.Net MVC

2. Benefits of using 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 logic.

View is equivalent to ASPX/HTML page.

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. MVC application life cycle.

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

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

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

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

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

A single controller class can handle multiple requests.

4. Filters in MVC

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 action method 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

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

6. Temp Data vs View Bag

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 short period time?
Here, a short period of time means for a subsequent request. Data stored in TempData will be lost after 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".


public class TestController : Controller
    {
        public ActionResult Book()
        {
            TempData["product"] = "MVC Ebook";
            return RedirectToAction("DisplayBook");
        }

        public string DisplayBook()
        {
            return TempData["product"].ToString();
        }

    }


7. What is Partial View?

Partial View provides re-usability features. Partial View is an effective way to break large View into smaller section. It is similar to UserControl in the traditional ASP.Net application. PartialView is a child view which rendered within a normal View page.
Partial View can be used within 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 Partial View.  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 View on View page using @Html.Partial("_PartialViewName")

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

9. HTML Helpers in MVC

HTML Helper methods are predefined methods in ASP.Net MVC to work with HTML forms.
HTML helper methods generate specific HTML tags on 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 MVC?

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

Scaffolding comes pre-installed from Visual Studio 2013 onwards.

12. 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 the web application.

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

When you create an MVC application, you may find Bundleconfig.cs file in 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 MVC?

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

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 write html directly in 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 request such as WebResource.axd, ScriptResource.axd

16. How to implement paging in MVC?

There could be multiple ways to manage pagination in 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 in 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 which help to implement paging on MVC application.

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. Means an application could have the different section such as Admin, Users or Customers, Moderator, Editor, Author etc.
In such condition, we can create Areas for all the sections. Area is used in large application only.

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 as 'ViewData' of type ViewDataDictionary, which contain key-value pair.

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

Read more about TempData, ViewBag, and ViewData

20. What is 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.
Unobtrusive scripts file automatically included in MVC application in Visual Studio. You may also get this library from Nuget.

21. How to handle an exception in 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 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 look 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 RouteConfgi 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?

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 a data from the server, a RequestVerificationToken is generated as shown in 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 developer.
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 dependency between two classes and helps to create independent classes.

You may also like -

ASP.Net MVC Tutorial
ASP.Net Web API Tutorial
Top 20 Web API interview questions and answers

Follow - SharePointCafe.Net

Comments

Popular

What's new in C# 6.0 language - All new features of C# 6.0 for developers

SharePoint Interview Questions and Answers