In this article, we are going to cover the top MVC interview questions and answers to help individuals pursue a career in web development. We will cover Asp.Net MVC questions and answers for freshers, intermediate, and experienced professionals.
What is MVC (Model View Controller)?
MVC is a software architecture pattern to develop web applications. It is abbreviated for Model View and Controller and these are also the main components that are responsible for shaping data and the business logic behind it.
Model: It represents the application data domain. In other words, applications business logic is contained within the model and is responsible for maintaining data
View: It represents the user interface, with which the end-users communicate. In short, all the user interface logic is contained within the VIEW
Controller: It is the controller that answers user actions. Based on the user actions, the respective controller responds within the model and choose a view to render that display the user interface. The user input logic is contained with-in the controller
What are the advantages of MVC?
There are below advantages of MVC;
Multiple view support: As the view for every data model and business logic is separate so it’s very easy to add and manage multiple views.
Change Accommodation: It’s become very easy to change views without changing any business logic because views are updated more frequently than business logic.
Separation of Concerns: Separation of Concerns is one of the core advantages of ASP.NET MVC. The MVC framework provides a clean separation of the UI, Business Logic, Model, or Data.
More Control: You can have more control over HTML, CSS, and JavaScript as compared to web forms.
Testability: As everything is separate so, it provides better testability of the application and good support for test-driven development too.
Lightweight: ASP.NET MVC framework doesn’t use View State so that’s why it reduces the bandwidth of the requests to a considerable level.
Full features of ASP.NET: You can use all features of the ASP.Net framework in ASP.Net MVC.
Explain the MVC application life cycle?
To creating a request object there are four basic steps:
- Fill Route
- Fetch Route
- Request Context Created
- Controller Instance Created
List out different return types of a controller action method?
The base type of all these result types is ActionResult.
ViewResult (View): This returns a webpage from an action method.
PartialviewResult (Partialview): This returns a part of a view that will be rendered in another view.
RedirectResult (Redirect): This redirects to any other controller and action method according to the URL.
RedirectToRouteResult(RedirectToAction,RedirectToRoute): This redirects to any other action method.
ContentResult (Content): This returns HTTP content type (i.e. text/plain) as the result of the action.
jsonResult(json): This returns a JSON message.
javascriptResult (javascript): This return type is used to return JavaScript code that will run in the browser.
FileResult (File): This returns the binary output in response.
EmptyResult: This returns nothing (void) in the result.
What are the Filters in MVC?
In MVC, the controller’s actions mostly have a one-to-one relation with a UI-Component/Control such as clicking a button or a link but they can also be used to perform some action before, after, or in between any particular operation. For this ASP.NET MVC provides a feature to add pre and post-action behaviors on the controller’s action methods.
Types of Filters
ASP.NET MVC framework supports the following action filters,
Action Filters: Action filters are used to implement logic that gets executed before and after a controller action executes.
Authorization Filters: Authorization filters are used to implement authentication and authorization for controller actions.
Result Filters: Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
Exception Filters: Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You can also use exception filters to log errors.
Action filters are one of the most commonly used filters to perform additional data processing, or manipulating the return values or canceling the execution of an action, or modifying the view structure at run time.
Explain what is routing in MVC? What are the three segments for routing important?
Routing is the URL pattern that is mapped together to a handler. The handler can be a physical file, such as ‘.aspx’ file in a Web Forms application, or a class that processes the request, such as a controller in an MVC application. In other ways, it helps you to define a URL structure and map the URL with the controller.
There are three segments for routing that are important,
- ControllerName
- ActionMethodName
- Parameter
What is the difference between Temp data, View, and View Bag?
ViewData:
- ViewData is used to pass data from controller to view.
- It is derived from ViewDataDictionary class.
- It is available for the current request only.
- Requires typecasting for complex data types and checks for null values to avoid an error.
- If redirection occurs, then its value becomes null.
ViewBag:
- ViewBag is also used to pass data from the controller to the respective view.
- ViewBag is a dynamic property.
- It is also available for the current request only.
- If redirection occurs, then its value becomes null.
- It doesn’t require typecasting for the complex data type.
TempData:
- TempData is used to pass data from the current request to the next request
- It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action.
- It requires typecasting for complex data types and checks for null values to avoid an error. Generally, it is used to store only one-time messages like error messages and validation messages.
What is Partial View in MVC?
A partial view is HTML that can be safely inserted into an existing View. These are used to componentize Razor views and make them easier to build and update. It is a reusable view that can be embedded inside another view.
Explain what is the difference between View and Partial View?
View:
- It contains the layout page.
- Before any view is rendered, the viewstart page is rendered.
- A view might have markup tags like the body, HTML, head, title, meta, etc.
- The view is not lightweight as compare to Partial View.
Partial View:
- It does not contain the layout page.
- The partial view does not verify for a viewstart.cshtml.We cannot put common code for a partial view within the viewStart.cshtml.page.
- Partial view is designed specially to render within the view and just because of that it does not consist of any markup.
- We can pass a regular view to the RenderPartial method.
What are HTML helpers in MVC?
Just like web form controls in ASP.NET, HTML helpers are used to modifying HTML. But HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an event model and a view state.
With MVC, you can create your own helpers, or use the built-in HTML helpers.
There following HTML helpers can be used to render (modify and output) HTML form elements:
- BeginForm()
- EndForm()
- TextArea()
- TextBox()
- CheckBox()
- RadioButton()
- ListBox()
- DropDownList()
- Hidden()
- Password()
Explain attribute-based routing in MVC?
In ASP.NET MVC 5.0 we have a new attribute route, by using the “Route” attribute we can define the URL structure. For example, in the below code we have decorated the “GotoAbout” action with the route attribute. The route attribute says that the “GotoAbout” can be invoked using the URL structure “Users/about”.
What is Razor in MVC?
Razor is a view engine that allows you to write server-side code on the view.
Why we use Razor?
- Compact & Expressive.
- Razor minimizes the number of characters and keystrokes required in a file and enables a fast coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote server blocks within your HTML. The parser is smart enough to infer this from your code. This enables a really compact and expressive syntax that is clean, fast, and fun to type.
- Easy to Learn: Razor is easy to learn and enables you to quickly be productive with a minimum of effort. We can use all your existing language and HTML skills.
- Works with any Text Editor: Razor doesn’t require a specific tool and enables you to be productive in any plain old text editor (notepad works great).
- Has great Intellisense:
- Unit Testable: The new view-engine implementation will support the ability to unit test views (without requiring a controller or web-server, and can be hosted in any unit test project – no special app-domain required).
- Razor code blocks are enclosed in @{ … }
- Inline expressions (variables and functions) start with @
- Code statements end with a semicolon
- Variables are declared with the var keyword
- Strings are enclosed with quotation marks
- C# code is case sensitive.
- C# files have the extension .cshtml
- The Razor View Engine prevents Cross-Site Scripting (XSS) attacks by encoding the script or HTML tags before rendering to the view.
Explain the need for display mode in MVC?
DisplayModes give you another level of flexibility on top of the default capabilities we saw in the last section. DisplayModes can also be used along with the previous feature so we will simply build off of the site we just created.
Using display modes involves 2 steps
- We should register Display Mode with a suffix for a particular browser using the “DefaultDisplayMode” class in Application_Start() method in the Global.asax file.
- View name for particular browser should be appended with suffix mentioned in the first step. You can see how to do in a desktop browser and mobile browser using below points:
- Desktop browsers (without any suffix. e.g.: Index.cshtml, _Layout.cshtml).
- Mobile browsers (with a suffix “Mobile”. e.g.: Index.Mobile.cshtml,Layout.Mobile.cshtml)
If you want design different pages for different mobile device browsers (any different browsers) and render them depending on the browser requesting. To handle these requests you can register custom display modes.
We can do that using DisplayModeProvider.Instance.Modes.Insert(int index, IDisplayMode item) method.
Explain the concept of MVC Scaffolding?
ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. It includes pre-installed code generators for MVC and Web API projects.
Scaffolding consists of page templates, entity page templates, field page templates, and filter templates. These templates are called Scaffold templates and allow you to quickly build a functional data-driven Website.
What is Bundling and Minification in MVC?
Bundling and minification are two new techniques introduced to improve request load time. It improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript).
Bundling:
It lets us combine multiple JavaScript (.js) files or multiple cascading style sheet (.css) files so that they can be downloaded as a unit, rather than making individual HTTP requests.
Minification:
It squeezes out whitespace and performs other types of compression to make the downloaded files as small as possible.
What is the Validation Summary in MVC?
The ValidationSummary helper method generates an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.
The ValidationSummary can be used to display all the error messages for all the fields. It can also be used to display custom error messages. The following figure shows how ValidationSummary displays the error messages.
@Html.ValidationSummary(false, "", new { @class = "text-danger" })
What is Database First Approach in MVC using Entity Framework?
Database First Approach is an alternative to the Code First and Model First approaches to the Entity Data Model which creates model codes (classes, properties, DbContextetc) from the database in the project, and that classes behave as the link between database and controller.
There is the following approach which is used to connect with the database to the application.
- Database First
- Model First
- Code First
What is ViewStart?
Razor View Engine introduced a new layout named _ViewStart which is applied to all views automatically. Razor View Engine firstly executes the _ViewStart and then starts rendering the other view and merges them.
What are Data Annotation Validator Attributes in MVC?
DataAnnotation plays a vital role in added validation to properties while designing the model itself. This validation can be added for both the client-side and the server-side.
- Required
- RegularExpression
- Range
- StringLength
- MaxLength
Explain RenderSection in MVC?
The first parameter to the “RenderSection()” helper method specifies the name of the section we want to render at that location in the layout template. The second parameter is optional and allows us to define whether the section we are rendering is required or not. For example
Explain in which assembly is the MVC framework is defined?
The MVC framework is defined in System.Web.MVC.
List out few different return types of a controller action method?
- View Result
- Javascript Result
- Redirect Result
- JSON Result
- Content Result
Mention what “beforFilter()”,”beforeRender” and “afterFilter” functions do in Controller?
- beforeFilter(): This function is run before every action in the controller. It’s the right place to check for an active session or inspect user permissions.
- beforeRender(): This function is called after controller action logic, but before the view is rendered. This function is not often used but may be required If you are calling render() manually before the end of a given action
- afterFilter(): This function is called after every controller action, and after rendering is done. It is the last controller method to run
Explain what are the steps for the execution of an MVC project?
The steps for the execution of an MVC project includes
- Receive the first request for the application
- Performs routing
- Creates MVC request handler
- Create Controller
- Execute Controller
- Invoke action
- Execute Result
How can we maintain session in MVC?
The session can be maintained in MVC in three ways tempdata, viewdata, and viewbag.
What is the difference between “ActionResult” and “ViewResult”?
“ActionResult” is an abstract class while “ViewResult” is derived from “AbstractResult” class. “ActionResult” has a number of derived classes like “JsonResult“, “FileStreamResult” and “ViewResult” .
“ActionResult” is best if you are deriving different types of views dynamically.
Mention what is the importance of NonActionAttribute?
All public methods of a controller class are treated as the action method if you want to prevent this default method then you have to assign the public method with NonActionAttribute.
Mention the order of the filters that get executed, if the multiple filters are implemented?
The filter order would be like
- Authorization filters
- Action filters
- Response filters
- Exception filters
Mention two instances where routing is not implemented or required?
Two instances where routing is not required are
- When a physical file is found that matches the URL pattern
- When routing is disabled for a URL pattern
What is the use of ViewModel in MVC?
ViewModel is a plain class with properties, which is used to bind it to a strongly-typed view. ViewModel can have the validation rules defined for its properties using data annotation.
Mention the Benefits of Area in MVC
Benefits of Area in MVC are as follows:
- It allows us to organize models, views, and controllers into separate functional sections of the application, such as administration, billing, customer support, and much more.
- It is easy to integrate with other Areas created by another.
- Also, easy for unit testing.
What is the use of Keep and Peek in “TempData”?
Once “TempData” is read in the current request, it’s not available in the subsequent request. If we want “TempData” to be read and also available in the subsequent request then after reading we need to call the “Keep” method as shown in the code below.
@TempData["MyData"];
TempData.Keep("MyData");
The more shortcut way of achieving the same is by using “Peek”. This function helps to read as well advise MVC to maintain “TempData” for the subsequent request.
string str = TempData.Peek("Td").ToString();
What is WebAPI?
WebAPI is the technology by which you can expose data over HTTP following REST principles.
How to perform Exception Handling in MVC?
In the controller, you can override the “OnException” event and set the “Result” to the view name which you want to invoke when an error occurs. In the below code you can see we have set the “Result” to a view named “Error”.
Why we use Html.Partial in MVC?
This method is used to render the specified partial view as an HTML string. This method does not depend on any action methods
What is a glimpse?
Glimpse is NuGet packages that help in finding performance, debugging, and diagnostic information. Glimpse can help you get information about timelines, model binding, routes, environment, etc.
What are the different kinds of Scaffold Templates and their uses?
The different kinds of Scaffold templates include page templates, field page templates, filter templates, and entity page templates. These templates support the building of a functional data-driven website.
Explain JSON Binding?
It allows the action methods to accept and model-bind data in JSON format. This is useful in Ajax scenarios like client templates and data binding that need to post data back to the server
Explain Bundle.Config in ASP.Net MVC4?
“BundleConfig.cs” in ASP.Net MVC4 is used to register the bundles by the bundling and minification system. Many bundles are added by default including jQuery libraries like – jquery.validate, Modernizr, and default CSS references.
What are AJAX Helpers in ASP.Net MVC?
AJAX Helpers are used to creating AJAX-enabled elements like Ajax-enabled forms and links which perform the request asynchronously and these are extension methods of AJAXHelper class which exists in namespace “System.Web.ASP.Net MVC”.
What is Layout in ASP.Net MVC?
Layout pages are similar to master pages in traditional web forms. This is used to set the common look across multiple pages
Explain Sections is ASP.Net MVC?
A section is the part of HTML which is to be rendered on the layout page. On the Layout page we will use the below syntax for rendering the HTML:
@RenderSection("TestSection")
And in child pages we are defining these sections as shown below :
@section TestSection {
<h1>Test Content<h1>
}
If any child page does not have this section defined then an error will be thrown so to avoid that we can render the HTML like this :
@RenderSection("TestSection", required: false)
What are Validation Annotations?
Data annotations are attributes that can be found in the “System.ComponentModel.DataAnnotations” namespace. These attributes will be used for server-side validation and client-side validation is also supported. Four attributes – Required, String Length, Regular Expression, and Range are used to cover the common validation scenarios.
What is RouteConfig.cs in ASP.Net MVC 4?
“RouteConfig.cs” holds the routing configuration for ASP.Net MVC. RouteConfig will be initialized on the Application_Start event registered in Global.asax.
Can a view be shared across multiple controllers? If Yes, How we can do that?
Yes, a view can be shared across multiple controllers. We can put the view in the “Shared” folder. When we create a new ASP.Net MVC Project, we can see the Layout page will be added in the shared folder, which is because it is used by multiple child pages.
In Server how to check whether the model has an error or not in ASP.Net MVC?
if (ModelState.IsValid)
{
//No Validation Errors
}
How to make sure Client Validation is enabled in ASP.Net MVC?
In Web.Config there are tags called
- ClientValidationEnabled
- UnobtrusiveJavaScriptEnabled
We can set the client-side validation just by setting these two tags “true”, then this setting will be applied at the application level.
< add key="ClientValidationEnabled" value="true" />
< add key="UnobtrusiveJavaScriptEnabled" value="true" />
What are Model Binders in ASP.Net MVC?
For Model Binding we will use a class called “ModelBinders”, which gives access to all the model binders in an application. We can create custom model binders by inheriting “IModelBinder”.
How we can register the Area in ASP.Net MVC?
When we have created an area make sure this will be registered in the “Application_Start” event in Global.asax. Below is the code snippet where area registration is done:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
}
What are child actions in ASP.Net MVC?
To create reusable widgets, child actions are used and this will be embedded into the parent views. Child action mainly returns the partial views.
How we can invoke child actions in ASP.Net MVC?
“ChildActionOnly” annotation will be used over action methods to indicate that this method is a child action. Like:
[ChildActionOnly]
public ActionResult ActionName()
{
//Your Code
return PartialView();
}
What is Dependency Injection in ASP.Net MVC?
It’s a design pattern that is used to develop a loosely coupled code. This is greatly used in software projects. This will reduce the coding in case of changes on project design so this is vastly used.
Explain the advantages of Dependency Injection (DI) in ASP.Net MVC?
- Reduces class coupling
- Increases code reusing
- Improves code maintainability
- Improves application testing
Explain Test-Driven Development (TDD)?
TDD is a methodology in which you write tests first before you write your code. In this approach, tests drive your application design and development cycles. You do not do the check-in of your code into source control until all of your unit tests pass.
Explain the tools used for unit testing in ASP.Net MVC?
Different tools are used for unit testing some name are as follow:
- NUnit
- Ninject 2
- xUnit.NET
- Moq
What is Representational State Transfer (REST) mean?
REST is an architectural style that uses HTTP protocol methods like GET, POST, PUT, and DELETE to perform CRUD actions on the data.
How to use Jquery Plugins in ASP.Net MVC validation?
We can use data annotations for validation in ASP.Net MVC. For runtime validation using Jquery then we can use Jquery plugins for validation e.g.:
If validation is to be done on customer name textbox then we can do as:
$('#CustomerName').rules("add", {
required: true,
minlength: 2,
messages: {
required: "Please enter name",
minlength: "Minimum length is 2"
}
});
How we can add multiple submit buttons in ASP.Net MVC?
Below is the sample code.
@using (Html.BeginForm("ActionName","ControllerName")
{
<input type="submit" value="SaveButton" />
<input type="submit" value="EditButton" />
}
Public ActionResult ActionName (string submit) //submit will have value either "SaveButton" or "EditButton"
{
// Your code
}
Can I set the unlimited length for the “maxJsonLength” property in the config?
No. We can’t set unlimited length for property maxJsonLength.
The default value is 102400 and the maximum value can be: 2147483644.
Can I use Razor code in Javascript in ASP.Net MVC?
Yes. We can use the razor code in javascript in cshtml by using <text> element.
< script type="text/javascript">
@foreach (var item in Model) {
< text >
//javascript goes here
< text >
}
< script>
How can I return string result from Action in ASP.Net MVC?
Below is the sample code for returning string in MVC.
public ActionResult ActionName() {
return Content("Hello World");
}
How to return the JSON from the action method in ASP.Net MVC?
Below is the Sample code for returning JSON in MVC.
public ActionResult ActionName() {
return JSON(new { prop0 = "Test0", prop1 = "Test1" });
}
What are the advantages of MVC over ASP.NET?
- Provides a clean separation of concerns among UI (Presentation layer), model (Transfer objects/Domain Objects/Entities), and Business Logic (Controller).
- Easy to UNIT Test.
- Improved reusability of model and views. We can have multiple views that can point to the same model and vice versa.
- Improved structuring of the code.
How we can add the CSS in MVC?
Below is the sample code snippet to add CSS to razor views
<link rel=”StyleSheet” href=”/@Href(~Content/Site.css”)” type=”text/css”/>
Thank you for reading. Please keep visiting and sharing within your community.
List of Best books on Asp.Net MVC:
- Professional ASP.NET MVC 5
- Pro ASP.NET MVC 5 (Expert’s Voice in ASP.Net)
- Pro ASP.NET Core 3 (Develop Cloud-Ready Web Applications Using MVC 3, Blazor, and Razor Pages)
- Murach’s Asp.Net Core MVC
List of Best Tutorials on Asp.Net MVC:
Leave a Reply