This MVC interview questions article will be very helpful to prepare for the MVC interview as we have focused on the top 25 frequently asked MVC Interview Questions and their answers based on actual interview experience.
Let’s get started to MVC Interview Questions and Answers!
MVC Interview Questions and Answers
Que 1. What is MVC? Explain MVC in detail.
MVC stands for Model View Controller. MVC is a software design pattern for web application development. It is a widely adopted and highly tested pattern, whose main purpose is to achieve a clean separation between three components of web applications. Those three components are:
Model
View
Controller
MVC Architecture Diagram
Learn in detail here: ASP.NET MVC
Que 2. What are the advantages of MVC?
Following are the core advantages of MVC:
- SoC (Separation of Concerns): Separation of Concerns is one of the core advantages of ASP.NET MVC. MVC Framework provides a clean separation of the UI (Presentation layer), Model (Transfer objects/Domain Objects/Entities), and Business Logic (Controller).
- Multiple View Support: The UI (User Interface) can display multiple views of the same data at the same time due to the separation of the model from the view,
- Parallel Development: Different developers can work on View, Controller logic, and Business logic in parallel.
- More Control: MVC Framework gives full control over HTML, CSS, and JavaScript compared to traditional WebForms.
- Test-Driven Development: Separation of Concerns provides better support for test-driven development as compared to traditional WebForms.
- Reusability: ASP.NET MVC improved reusability of model and views. We can have multiple views that can point to the same model and vice versa.
- Lightweight: MVC framework doesn’t use View State hence it reduces the bandwidth of the requests to a great extent.
- Full features of ASP.NET: ASP.NET MVC is built on top of the ASP.NET framework hence you can use most of the features of the ASP.NET can be used. Example – membership providers, roles, etc.
Que 3. What is Routing in MVC?
In MVC, routing is a mechanism that decides which action method of a controller class to execute based on the URL. It is a mechanism to process the incoming request from the browser and execute the particular action rather than physical or static files.
In traditional Web Forms, we have physical files to handle the different requests but we don’t have it in MVC. Routing is the only option to map action method to request. Routing helps to remove the Physical File path dependency and make URL self-explanatory
Routing help to define a URL pattern and then map the URL with the controller. This URL is self-explanatory.
url:{controller}/{action}/{id} (optinal parameter)
Example: http://localhost:80/Student/Index/1
Student: Controller
Index: ActionMethodName
1: Id Parameter value
Types of Routing:
There are two types of routing
- Convention based routing: Default routing. to define this type of routing, we call the MapRoute method and set its unique name, URL pattern, and specify some default values.
- Attribute Routing: Introduced in ASP.NET MVC 5. Specify the Route attribute in the action method of the controller.
Que 4. What is attribute routing in MVC?
//Example:
public class StudentController: Controller
{
[Route("Students/Class")]
public ActionResult RedirectToClass()
{
return View();
}
}
Optional Parameter: We can specify an optional parameter in the URL pattern by using a question mark (“?”) to the route parameter. We can also define the default value by using parameter=value.
//Example:
public class StudentController: Controller
{
[Route("Students/{class ?}")]
public ActionResult GetDetails(string class)
{
ViewBag.Message = "Attribute Routing with Optional Parameter!";
//get student details of ... class
return View();
}
[Route("Students/{class="MCA"}")]
public ActionResult GetDetails(string class)
{
ViewBag.Message = "Attribute Routing with Default Value!";
//get student details of MCA class
return View();
}
}
Que 5. What is Razor View Engine in MVC?
Razor was designed specifically for view engine syntax. It is a markup syntax that can be used to write HTML and server-side (C# or VB.NET) code on a web page. Razor is not a new programming language itself, however, it uses C# syntax for embedding code in a web page. It is a simple syntax templating engine.
//Example:
<div>
@{
bool permission = true; //code to set actual value to permission variable
if (permission)
{
<div>Click <a href="/Student/Records">Here</a> to see Students Records</div>
}
else
{
<div>Sorry, You don't have permission to see Students Records!</div>
}
}
</div>
Que 6. What are ViewData and ViewBag?
ViewData
Example:
//C# - Controller's action
public ActionResult Students(int id)
{
//define ViewData
ViewData["StudentDetails"] = GetStudentDetails(id);
//other code here
return View();
}
//.cshtml code to read ViewData
//null check
@if(ViewData["StudentDetails"] != null)
{
//typecasting
Student student = (Student) ViewData["StudentDetails"];
}
ViewBag
Example:
//C# - Controller's action
public ActionResult Students(int id)
{
//define ViewBag
ViewBag.StudentDetails = GetStudentDetails(id);
//other code here
return View();
}
//.cshtml code to read ViewBag data
int studentId = ViewBag.StudentDetails.Id;
Que 7. What is TempData?
Example:
//C# - Controller's action
public ActionResult Students(int id)
{
//define TempData
TempData["StudentDetails"] = GetStudentDetails(id);
//other code here
return View();
}
//.cshtml code to read TempData
//null check
if (TempData["StudentDetails"] != null)
{
//typecasting
Student student = (Student) TempData["StudentDetails"];
}
Que 8. Difference between ViewData, View Bag and tempData
ViewData | ViewBag | TempData |
---|---|---|
ViewData is Key-Value pair | ViewBag is a type object | TempData is Key-Value pair |
ViewData is a dictionary object | ViewBag is Dynamic property | TempData is a dictionary object |
ViewData is Faster than ViewBag | ViewBag is slower than ViewData | No compare |
ViewData is available from MVC 1.0 | ViewBag introduced in MVC 3.0 | TempData is available from MVC 1.0 |
Typecasting required | Typecasting does not require | Typecasting required |
null check required | null check does not require | null check required |
Works for the current request only | Works for the current request only | Works for the current and subsequent requests |
The value becomes null once redirect occurs | The value becomes null once redirect occurs | TempData is used to pass data between two consecutive requests |
Que 9. What is Partial View?
In traditional Web Forms, User Controls are used to keep common information so that it can be reuse across the application. In ASP.NET MVC, Partial View is used for the same (reusability) purposes.
A Partial View is a small HTML code that can be stored in a file and that can be inserted into multiple views.
Important Points:
- Partial Views are reusable views
- Following two methods are available to render partial views
1)Html.Partial()
2)Html.RenderPartial() - The partial view doesn’t contain any markup or layout page as it renders within the View
- Partial View shared with multiple views so these are kept in the shared folder
This is one of the most frequently asked MVC interview questions.
Que 10. What is the use of ViewModel in MVC?
ViewModel is a plain class that contains the required properties to represents the data on the view/page. ViewModel is used to transfer required data from controller to view.
ViewModel can have the validations to the properties using data annotations. ViewModel is different from the domain model. View models can have properties from different domain models.
Que 11. What are HTML Helpers in MVC?
In ASP.NET MVC, HTML Helpers are like traditional ASP.NET WebForms controls. HTML helpers are used to modifying HTML as ASP.NET Web Form controls, however, ASP.NET MVC HTML helpers are more lightweight compared to traditional WebForm controls as it does not have a view state and an event model.
An HTML helper is a method that returns an HTML string and directly rendered on the HTML page. In ASP.NET MVC, we can create our custom helpers by overriding the “HtmlHelper” class or we can use the built-in HTML helpers.
Standard HTML Helpers:
- Html.TextBoxFor
- Html.TextAreaFor
- Html.PasswordFor
- Html.HiddenFor
- Html.CheckBoxFor
- Html.RadioButtonFor
- Html.DropDownListFor
- Html.ListBoxFor
- Html.ActionLink
Example: .cshtml
Que 12. What is ViewStart Page in MVC?
Example:
Que 13. What are the Actions in MVC?
In MVC, a controller class exposes actions. An action is a method of a controller that gets executed when a resource is requested from the server (when you enter a URL in the browser).
Example: http://localhost/Student/Index/1
When you enter the above URL in the browser then Index() method of StudentController class gets executed. This Index() method is nothing but Action. Actions are responsible to return the result (view or JSON data).
Example:
//C# - Controller's action
public ActionResult Index(int? id)
{
//code/logic here
return View();
}
Que 14. What are the types of Action Results in MVC?
A controller’s actions are responsible to return something (view or JSON data) called an action result.
Following are the subtypes of ActionResults
- ViewResult (View): Return a webpage (HTML and Markup).
- PartialviewResult (Partial View): Returns partial view (use with Ajax request to update a part of the page).
- EmptyResult: Return no (void) result.
- RedirectResult (Redirect): Redirect to any other controller and action (redirect to the new URL).
- RedirectToRouteResult (RedirectToAction, RedirectToRoute): Redirect to any other action method.
- ContentResult (Content): Return text result.
- JSONResult (JSON): Return a JSON message.
- JavaScriptResult (JavaScript): Return JavaScript code.
- FileResult (File): Return binary output.
Let’s move to advance MVC Interview Questions and Answers section
Advanced MVC Interview Questions and Answers
Que 15. What are the Filters in MVC?
In ASP.NET MVC, the user request is routed to the related controller and controller then find and execute the appropriate action method. For example, when student click on submit button then submit request routed to StudentController and then StudentController execute Submit action method. However, many times you will have a situation where you want to perform some action before or after an action method executes. ASP.NET MVC provides filters to achieve this functionality.
In ASP.NET MVC, Filter is a class where custom logic can be implemented which needs to execute before or after an action method execute. These filters can be applied in the following two ways:
- Action method: Apply a filter attribute to an action method
- Controller class: Apply a filter attribute or implement a related interface to the controller class.
Types of Filters:
ASP.NET MVC framework supports the following action filters:
- Authorization Filters: Implements the IAuthorizationFilter attribute. It is used to implement authentication and authorization for controller actions.
- Action Filters: Implements the IActionFilter attribute. It is used to implement logic that gets executed before and after a controller action executes. Learn more about action filters here.
- Result Filters: Implements the IResultFilter attribute. It contains 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: Implement the IExceptionFilter attribute. This filter can be used to handle errors raised by either your controller actions or controller action results. You can also use exception filters to log errors. Exception filters executed at last.
Filters are executed in the order as listed above. Authorization filters are always executed before action filters and exception filters are always executed after every other type of filter.
Que 16. How to change the action name in MVC?
//Example:
[ActionName(“FindAllStudents”)]
public ActionResult GetAllStudents()
{
return View();
}
In the above code snippet, we have applied ActioName(“FindAllStudents”) attribute to the GetAllStudents action method. Now, the caller has to use FindAllStudents instead of GetAllStudents.
http://localhost/student/FindAllStudents – this will invoke action method
http://localhost/student/GetAllStudents – this will not work
Que 17. What is Bundling and Minification in MVC?
Bundling and minification techniques are introduced in MVC 4 to improve the request load time of ASP.NET MVC Web Application by reducing the number of HTTP requests and reducing the size of requested files.
Bundling: Bundling is a technique to combine or bundle multiple JavaScript or CSS (cascading style sheet) files into one so it can make a single HTTP request to download a bundled file instead of making HTTP requests to each file.
Minification: Minification is a technique to optimize code in a script or CSS file by squeezing out whitespace and performing other types of compression. So the downloaded files will be small.
BundleConfig.cs is used to register the bundles by the bundling and minification system.
This is not only frequently asked MVC Interview Questions but also very important techniques to boost the performance of your MVC application.
Que 18. What is Scaffolding in MVC?
Scaffolding is a code generation framework for ASP.NET Web applications. The use of Scaffolding can reduce the amount of time to develop standard data (CRUD) operations in the project. In ASP.NET MVC, you can add scaffolding to your application to generate code that interacts with the data models.
ASP.NET Scaffolding work with Microsoft Visual Studio 2013 or higher version.
Que 19. What is RouteConfig.cs in MVC?
RouteConfig.cs contains the routing configuration for MVC application. RouteConfig will be initialized on the Application_Start event registered in the Global.asax. RouteConfig.cs resides under App_Start folder.
Example:
Que 20. How to enable Attribute Routing in MVC?
Call the “MapMvcAttributeRoutes()” method in the RegistearRoutes method of RoutingConfig class to enable attribute routing in MVC application.
Example:
public class RouteConfig
{
public static void RegistearRoutes(RouteCollection routes)
{
routes.IgnoareRoute(“{resource}.axd/{*pathInfo}”);
//enabling attribute routing
routes.MapMvcAttributeRoutes();
//convention-based routing
routes.MapRoute
(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
);
}
}
Que 21. What are Validation Annotations in MVC?
Date Annotations are validations that can be applied in the models to validate the user’s input. ASP.NET MVC uses DataAnnotations attributes to implement server-side as well as client-side validations. System.ComponentModel.DataAnnotations namespace needs to import to use data annotations in your application.
Standard Data Annotation Attributes:
- Required – Indicates that the property is a required field
- DisplayName – Defines the text we want to be used on form fields and validation messages
- StringLength – Defines a maximum length for a string field
- Range – Define a maximum and minimum value for a numeric field
- CustomValidation – Specified custom validation method to validate the field
- EmailAddress – Validates Email address format
- Bind – Lists fields to exclude or include when binding parameter or form values to model properties
- MaxLength – Define maximum length for a string field
- MinLength – Define minimum length for a string field
- RegularExpression – Specifies Regular Expression. Set a regex pattern to the property.
Example:
public class Student
{
public int StudentId { get; set; }
[Required]
public string Name { get; set; }
[Range(15,50)]
public int Age { get; set; }
}
Que 22. What is the use of a Glimpse in MVC?
Glimpse is an open-source tool (NuGet package) that provides detailed performance, debugging, and diagnostic information in the ASP.NET MVC application. Glimpse is the client-side debugger.
Enable Glimpse:
To enable Glimpse, navigate to the local URL link and click the Turn Glimpse On button.
http://localhost:<port no.>/glimpse.axd
Que 23. What is Layout in MVC?
Example:
Que 24. What are Non Action methods in MVC?
In ASP.NET MVC, by default, all the public methods are considered as Action methods. If you have a requirement to create a public method but not an action method then you have to use the NonAction attribute for that method.
NonAction attribute indicates that a public method of a Controller is not an action method.
Example:
public class StudentController : Controller
{
public StudentController()
{
}
[NonAction]
public Student GetStudentById(int id)
{
return studentList.Where(s => s.Id == id).FirstOrDefault();
}
}
Que 25. What is the HelperPage.IsAjax Property in MVC?
Example:
public static bool IsAjax { get; }
Summary
These are the frequently asked MVC interview questions and answers based on our interview experience. I hope this article will be helpful for your MVC interview preparation.
- C# Interview Questions and Answers
- .NET Interview Question and Answers
- Azure Interview Questions and Answers
- WEB API Interview Questions and Answers
- ASP.NET Interview Questions and Answers
- AWS Interview Questions and Answers
- SQL Interview Questions and Answers
- Angular Interview Questions and Answers
- React Interview Questions and Answers
- JavaScript Interview Questions and Answers
- JQuery Interview Questions and Answers
- Behavioral Questions and Answers