upGrad KnowledgeHut SkillFest Sale!

MVC Interview Questions

MVC is used to develop UI and applications with a clear separation of concerns, making it easier to develop and maintain complex applications. Its modularity and flexibility allow each component to be developed independently and swapped out as needed. Have you planned for an MVC interview for any fresher, intermediate or expert role? If yes, then this guide on MVC interview questions prepared by our team of experts is aimed at helping you excel in your upcoming interviews. These MVC interview questions and answers will equip you to answer the questions on Model, View, and Controller in MVC, Razor View Engine, ViewData, ViewBag and TempData, etc. Going through these MVC interview questions and answers will help your IT dreams come true. Prepare well and crack your interview with ease and confidence!

  • 4.8 Rating
  • 34 Question(s)
  • 25 Mins of Read
  • 13302 Reader(s)

Beginner

MVC architecture represents the domain-specific data and business logic. It maintains the data of the application, model data hold the data in public property.

We can also manipulate the data in the business logic layer

Namespace mvc.Models
{
   public class Student
{
   public int StudentId { get; set; }
   public string StudentName { get; set; }
   public int Age { get; set; }
}
}

In Model, we can apply validation to the property using Data Annotation instead of applying on the client side. For adding data Annotation we need to add the reference “System.ComponentModel.DataAnnotations assembly”

Like we apply on StudentId

Eg. 

[Display(Name=”StudentId ”)]
[Required(ErrorMessage=”StudentId is Required”)]
Public int StudenId {get;set;}

View View is the User Interface where The user can display its own data and can modify its data, In this, the data is passed from the model to the view. The view has a different folder with the same name as of controller and has different views in it of different actions.

There are 3 types of Views in MVC

  • User View : To create this view use page template. The inherited class name will be available in <%@ page directive with inherits attributes.
  • Master Page View : To create a master page view we use a template known as “MVC2 view master page.it have a default extension of.master.
  • Partial View : Partial View is the same as UserController in asp.net it is inherited from the System.Web.Mvc

Controller: It is the most essential part of the MVC in asp.net since it is the first recipient which interacts with HTTP and finds the model and actions. So it is the controller which decides which model should be selected and how to carry the data from the respective view, a controller is inherited from the System.Mvc.Controller. The routing map of the controller is decided in RouteConfig.cs which is under App Start Folder.

Eg, http://localhost:61465/Employee/Mark

Where Employee is a controller name and mark is the action.

The advantages of MVC of ASP.NET are :

  1. It provides a separation feature where one developer can work on Controller and the other can work on View to create the business logic layers of the web application. This results that the MVC model is much faster than the other programming patterns.
  2. The Duplication of code is very limited in MVC because it separates data and business logic from the display by creating multiple views for a model.
  3. It can work with a javascript framework which makes it work with the Pdf files and other widgets. Its asynchronous techniques help the developer to develop and load the application faster.
  4. It is very helpful when we want some frequent changes in the web application like changing colours, fonts, screen layouts, and adding new device support for mobile phones or tablets.it is very simple to add views since adding views not affect on the model, so changing in models does not affect the architecture of the web application.
  5. MVC web applications are very useful to develop the SEO platform. This method of development of architecture is commonly used in the Test Driven Development applications. Moreover, Scripting languages like JavaScript and jQuery can be integrated with MVC to develop feature-rich web applications. Projects that are developed with the help of MVC model can be easily developed with lesser expenditure and within less time too. As a result, today organizations are looking for development of web applications based on MVC architecture for cost and time benefits. There are many companies who provide MVC development services to develop web applications that satisfy every requirement of the clients.

Razor is not a programming language but an HTML markup language which is written on the server side using C#. Razor does not have the tie-up with Asp.net mvc. It has implemented a view engine to use razor view to produce the HTML output. It uses the @{....} syntax. It uses a semicolon to end the statement, it has .cshtml as file extensions.inline expression also uses the @ expression’

Conditions with if statement

It starts with a code block and its condition is written in parenthesis.  the code which needs to be executed is written inside braces.

@{var Price=60;}
<html>
<body>
<if(Price>60)
{
<p>This is paragraph</p>
}
</body>
</html>

In the above example, we have declared var price has a value of 60 and we are using if statement which is validating price. the code written in side braces gets executed,if price value is greater than 50.

In razor, we have a different type of block statements available, which are

1.Single Statement Block and Inline Expression: It is the same as we discussed above that it is the block of code which is executed in the single line statement.

          @{var series=4;}
<p>MVC series :@series</p>
<p>Razor Message:@RazorMessage</p>

2.Multiple Statement Block with Inline Expressions : In this we declare all the variable in single @{....} and each variable is ended with the semi colon

@{
            Var a =”This is Razor Syntax”;
            Var b = DateTime.Now.DayOfWeek;
            Var c = a + “Date on ”+b;
}
<p>Razor Message:@HomeMessage</p>

So it is better to declare the variable at the top of the view because if we declare the variable at the top then it can be used in all inline block of statement written on that view and if we declare this variable at the middle order of view then we cannot use at the top statement written in @{....}.

This is one of the most frequently asked MVC interview questions for freshers and experienced in recent times.

When a programmer send the request and when it goes to the action method it sees the return type of  the action result and produces the desired result on the view after that,

Action Result is a result of action methods or return types of action methods. Action result is an abstract class.

Different types of ActionResult are-

  1. View Result
  2. Partial View Result
  3. Redirect Result
  4. Redirect To Action Result
  5. Redirect To Route Result
  6. Json Result
  7. File Result
  8. Content Result

1.View Result: View Result is very simple Action Result type it is a class which is derived from the ViewResultBase class and viewResultBase Class is derived from the ActionResult, View results in the data in view which is defined in the model. View page is a simple HTML page. Here view page has “.cshtml” extension

         Eg,

 Public ViewResult About()
{
ViewBag.Message=”The View Result is here”;
Return View();
}

2.Partial View Result : The partial view is a class which is also derived from action result class. When we create a partial view it is created in the shared folder with the .cshtml extensions. If we don't have the partial view we cannot access the partial view, Partial view is one of the views that we can call inside the Normal view page.

Eg. 

public partialViewResult Index()
{
Return PartialView(“_PartialView”);
}

3.Render Result: it helps in redirecting the request to the specific url ,if the url is wrong then it gives the Error 404

Eg  

public RedirectResult Index()  
{  
return Redirect("Home/Contact");  
}

4.Redirect to Action Result: it helps in redirecting the request to action through the controller it is not necessary to mention the controller name in RedirectToAction() if controller is not there then it will redirected to the action which matches in RedirectToAction() ,if action does not find on the page then it will give the error 404.

public ActionResult Index()  
{  
return RedirectToAction("Login", "Account");  
}

5.Json Result : Json result is a significant Action Result in MVC. It will return response in the format of key value pairs.it return json if we call json method

Eg:

 Public ActionResult Index()   
{  
var persons = new List<Person1>  
 {  
new Person1
{
Id=1, FirstName="Harry", LastName="Potter"
},      
new Person1
{
Id=2, FirstName="James", LastName="Raj"
}   
};   
return Json(persons, JsonRequestBehavior.AllowGet);
 }

ViewData:ViewData is used when we want to transfer the data from controller to view it as a dictionary which is used to transfer the data in the form of key-value pair where key is always string, we can transfer the data from the controller to view but it is not possible to transfer the data from view to controller using ViewData.

Eg, 

ActionResult Index()
{
IList<Student> studentList = new List<Student>();
studentList.Add(new Student(){ StudentName = "Bill" });
studentList.Add(new Student(){ StudentName = "Steve" });
studentList.Add(new Student(){ StudentName = "Ram" });
ViewData["students"] = studentList;
return View();
}

Access ViewData in a Razor View

<ul>
@foreach (var std in ViewData["students"] as IList<Student>)
{ <li> @std.StudentName </li>
}
</ul>

Add KeyValuePair in ViewData

public ActionResult Index()
{
ViewData.Add("Id", 1);
ViewData.Add(new KeyValuePair<string, object>("Name", "Bill")); ViewData.Add(new KeyValuePair<string, object>("Age", 20));
return View();
}

Viewdata request is last till the current web request, it the cleared the view data when there is the redirection, before using the viewdata we need to cast it. We can use the temp data in MVC 1.0 and its above version.it requires the type conversion while we are enumerating. It will throw the error when there is the redirection of a request.

ViewBag : ViewBag is used to when we want to transfer the small amount of data from Controller to view or we can say when we want to transfer temporary data (which is not included in model) from the controller to the view.its derived from the controller base Class which is a base class for all the controller,it attaches the name property with dot notation and assign the string value in it and using razor syntax @ to get the server side code,

You can assign any number of properties and values to ViewBag. What so ever time you will assign the values to the viewbag it will consider the last value defined in the property.

namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
IList<Student> studentList = new List<Student>()
{
new Student()
{
StudentID=1, StudentName="Steve", Age = 21
},
new Student()
{
StudentID=2, StudentName="Bill", Age = 25
},
new Student()
{
StudentID=3, StudentName="Ram", Age = 20
},
new Student()
{
StudentID=4, StudentName="Ron", Age = 31
},
new Student()
{
StudentID=5, StudentName="Rob", Age = 19
}
}; // GET: Student
public ActionResult Index()
{
ViewBag.TotalStudents = studentList.Count();
return View();
}
}
}

On view page we can access the data by

<label>Total Students:</label> @ViewBag.TotalStudents

TempData: ASP.NET MVC can be used to store temporary data which can be used in the subsequent request.it is very useful when we want to transfer the data from one action to another action or from one controller to another controller, the data is passed in the form of key-value pair

public class HomeController : Controller

{ // GET: Student
public HomeController()
{
}
public ActionResult Index()
{
TempData["name"] = "Test data";
TempData["age"] = 30;
return View();
}
public ActionResult About()
{
string userName;
int userAge;
if(TempData.ContainsKey("name"))
userName=TempData["name"].ToString(); if(TempData.ContainsKey("age"))
userAge = int.Parse(TempData["age"].ToString());
return View();
}
}

Life span for temp data is very small. Data in TempData can persist only upto next view or upto next controller action. If we want to take data in TempData to successive requests then we need to call a method: TempData.Keep(), to keep the data persists for next request.

Expect to come across this, one of the most important MVC interview questions for experienced professionals in programming, in your next interviews.

Intermediate

ASP.NET MVC has provided ViewBag and ViewData to transfer data from the controller to view. Let’s look into these in deep:

ViewData: ViewData is derived from the ViewDataDictionary, hence it stores data in key Value format like a dictionary, where the Keys are in String and represents the name of an object while Values will be objects. As data in ViewData is stored in object form, so it is required to cast the data to its original type before using it. It is also required to do the NULL check while retrieving data. The life span of ViewData is from Controller to View.

Example: ViewData["Message"] = "Test Data";

ViewBag: ViewBag is a Wrapper that is built around the ViewData. It is a dynamic property and it makes use of the C# 4.0 dynamic features. Like ViewData, it is not required to do typecasting data before use. The life span of ViewBag is from Controller to View only.

Example: ViewBag.Message = "Test Data";

TempData: TempData is derived from TempDataDictionary class and it is also a  Dictionary object i.e. Keys and Values where Keys are in String and represents the name of the object while Values will be objects. It is required to do typecasting of data before using it as the data is in the object format and it also requires NULL checks while retrieving. The life span of TempData is larger than of ViewData and ViewBag. TempData can be used for passing value from Controller to View and from Controller to Controller. It is also available for Current and Subsequent Requests. 

Example: TempData["Message"] = "Test temp data";

The base type for all the return types of action method is “Action Result”. Below are the various return types that can be used to return results from a controller action method. 

  1. ViewResult (View): This return type is used to return a webpage from the action method.
  2. PartialviewResult (Partial view the ): This is used to send part of a view that is going to render inside another view.
  3. RedirectResult (Redirect): This is used to redirect to any other controller and action method based on the URL.
  4. RedirectToRouteResult (RedirectToAction, RedirectToRoute): This is used  to redirect to any other action method.
  5. ContentResult (Content): This is used to return HTTP content type text/plain as the result.
  6. JSONResult (JSON): This is used to return JSON as a result.
  7. JavascriptResult (javascript): This is used to return the JavaScript code that will run in the browser.
  8. FileResult (File): This is used to return binary output as a response.
  9. EmptyResult: This is used when nothing (void) to return.

ASP.NET MVC 2 introduced Area. It allows us to partition the large application into smaller units/folders where folder unit contains separate MVC folder structure, same as default MVC folder structure. For example, big enterprise applications can have different modules like admin, finance, HR, marketing, etc. So an Area can contain separate MVC folder structure for all these modules.

Areas are basically the logical grouping of Controller, Models and Views and other related folders for a module in MVC applications. Using areas helps to write more maintainable code for an application cleanly separated according to the modules.

Benefits of Area in MVC

  1. It allows us to organize models, views, and controllers into separate functional sections of the application.
  2. Easy to integrate.
  3. Easy to do unit tests.

Routing is the way to locate the action that matches the URI in ASP.NET MVC. Sometimes it is required to have a route that is different in pattern from other routers in the application and is not possible to configure it by making use of convention-routing.

In MVC 5, a new type of routing is introduced, called attribute routing. Attribute Routing has given more flexibility to configure routes that are specific to any controller/action. Like the name says, routes are added as an attribute to controller/action. This type of routing provides you more control over the URIs in your web application.

Example of Attribute Routing:

[Route(“{category:int}/{categoryName}”)]
public ActionResult Show(int categoryId) { … }

To enable attribute routing, call MapMvcAttributeRoutes during configuration.

Route Prefixes:

Route Prefixes are the prefix for any route that we want to apply, this is done by defining the route prefix on a controller so that all the action methods inside it can follow the prefix.

[RoutePrefix("category")]
public class CategoryController : Controller
{ .... }

Like in ASP.Net web forms, we have a toolbox for adding controls (like textbox, label, dropdown) on any particular page. Now, in the ASP.NET MVC application, there is no toolbox available to add controls on the view. ASP.NET MVC provides HtmlHelper class which contains various methods that help you create HTML controls programmatically. All HtmlHelper methods generate HTML and return the result as a string. The final HTML is generated at runtime by these functions. The HtmlHelper class is designed to generate UI and it should not be used in controllers or models.

The following is the list of Html Helper controls.

Html.Beginform

Html.EndForm

Html.Label

Html.TextBox

Html.TextArea

Html.Password

Html.DropDownList

Html.CheckBox

Html.RedioButton

Html.ListBox

Html.Hidden

Below are Strongly Type Html Helper methods, this will allow us to check compile-time errors. 

We get Model's Property intelligence at Runtime.

Html.LabelFor

Html.TextBoxFor

Html.TextAreaFor

Html.DropDownListFor

Html.CheckBoxFor

Html.RadioButtonFor

Html.ListBoxFor

Html.HiddenFor

HtmlHelper class generates html elements. For example, @Html.ActionLink("Create New", "Create") would generate anchor tag <a href="/Student/Create">Create New</a>.

A staple in Spring MVC interview questions for experienced professionals, be prepared to answer this one using your hands-on experience.

Like in ASP.Net web forms, we have a toolbox for adding controls (like textbox, label, dropdown) on any particular page. Now, in the ASP.NET MVC application, there is no toolbox available to add controls on the view. ASP.NET MVC provides HtmlHelper class which contains various methods that help you create HTML controls programmatically. All HtmlHelper methods generate HTML and return the result as a string. The final HTML is generated at runtime by these functions. The HtmlHelper class is designed to generate UI and it should not be used in controllers or models.

The following is the list of Html Helper controls.

Html.Beginform

Html.EndForm

Html.Label

Html.TextBox

Html.TextArea

Html.Password

Html.DropDownList

Html.CheckBox

Html.RedioButton

Html.ListBox

Html.Hidden

Below are Strongly Type Html Helper methods, this will allow us to check compile-time errors. 

We get Model's Property intelligence at Runtime.

Html.LabelFor

Html.TextBoxFor

Html.TextAreaFor

Html.DropDownListFor

Html.CheckBoxFor

Html.RadioButtonFor

Html.ListBoxFo

Output Caching is part of state management. Output Caching is one of the types of Action Filter. Output caching can help to improve the performance of MVC application by caching the content returned by any controller action. It reduces the server and database round trips and also reduces network traffic.

Enabling Output Caching

Output Caching can be enabled by adding attribute: [OutputCache] to either on controller or action method. If added to the top of the controller then output caching is enabled for all the action methods of that controller.

Example:

public class HomeController : Controller
{
    [OutputCache(Duration=10, VaryByParam="none")]
    public ActionResult Index()
    {
       return View();
    }
}

Where the content is Cached

By default, the content is cached in three locations: web server, proxy server, and web browser. But we can control where exactly we want to cache the content by modifying the location property of [OutputCache].

Example:

[OutputCache(Duration=3600, VaryByParam="none", Location=OutputCacheLocation.Client)]
 public ActionResult Index()
    {
       return View();
    }

Any of the value for Location property can be selected as follows:

  • Any (this is the default value selected)
  • Client
  • Downstream
  • Server
  • None
  • ServerAndClient

Creating a Cache Profile

MVC has provided one more feature to create a caching profile. Creating a caching profile on a configuration file (web.config) provides a couple of advantages like:

  1. Manage how controller action cache the content. We can create one cache profile and apply it to several controller and controller actions.
  2. Modify the cache configuration without recompiling the application

Example:

<caching>
<outputCacheSettings>
    <outputCacheProfiles>
        <add name="Cache1HourTest" duration="3600" varyByParam="none" Location=OutputCacheLocation.Any/>
    </outputCacheProfiles>
</outputCacheSettings>
</caching>

Html.HiddenFor

HtmlHelper class generates html elements. For example, @Html.ActionLink("Create New", "Create") would generate anchor tag <a href="/Student/Create">Create New</a>.

Partial view is a reusable view like the user control in ASP.NET, which can be used as a child view in multiple other views. It reduces the duplicate code in the system by reusing the same partial view in multiple views. You can use the partial view in the layout view, as well as other content views.

To render the partial view in the parent view we use  HTML helper methods: Partial() or RenderPartial() or RenderAction(). Each method has different purposes, as follows:

  • The partial helper method renders the given partial view. It accepts partial view name as a string parameter and returns MvcHtmlString. 
  • RenderPartial helper method is like the Partial method but it returns void and writes resulted in HTML of a specified partial view into an http response stream directly.
  • RenderAction helper method invokes a specified controller and action and renders the result as a partial view. 

The majority of the websites are making use of Javascript and CSS files to improve the usability and look and feel of websites. So often on these pages, you will find multiple <script> and <link> tags. Each time the browser runs across these tags, make the call to the server to download the respective script and CSS files.  

So the number of Javascript and CSS files in our application, more the requests made to the server which leads to increase the time to load the page and make it functional.

In MVC 4.5 two new techniques are introduced to reduce these requests and improve the request load time. These two techniques are:

  1. Bundling
  2. Minification

Bundling

As the name says, Bundling combines the multiple files of the same type into a single file. So like if we have multiple script files use in an application, Bundling will combine all these script files into one single script file. Since the number of files is reduced, hence the number of HTTP requests is also reduced and this can improve first-page load performance.

In MVC Application there is a file called BundleConfig.cs in App_Start folder where we can add similar files into one bundle. We can add/register multiple bundles here.

Minification

Minification technique helps to reduce the size of the files. This technique applies to the bundled files. It applies various code optimizations to scripts and CSS like reducing/removing unnecessary white spaces and comments, shortening variable names.

We can enable/disable Bundling and minification through Web.config file as: 

<system.web>
<compilation debug="true" />
<!-- Lines removed for clarity. -->
</system.web>

ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Scaffolding quickly adds code that interacts with data models and reduces the amount of time to develop standard data operations in the project. With the help of scaffolding, we can add views of Index, Create, Edit actions very easily and the code is itself added for each view and action methods.

Scaffolding consists of Scaffold templates like page templates, entity page templates, field page templates, and filter templates. These templates allow to quickly build a functional data-driven Website. They are used to generate code for basic CRUD operations against the database with the help Entity Framework. These templates the Visual Studio T4 templating system to generate views for basic CRUD operations with the help of Entity Framework

Below are the options in AJAX helpers –

  • Url: This is the request URL.
  • Confirm: This is used to specify the message which is to be displayed in the confirm box.
  • OnBegin:  method name to be given here and this will be called before the AJAX request.
  • OnComplete:  method name to be given here and this will be called at the end of AJAX request.
  • OnSuccess: method name to be given here and this will be called when AJAX request is successful.
  • OnFailure: method name to be given here and this will be called when AJAX request is failed.
  • UpdateTargetId: Target element which is populated from the action returning HTML.

Authentication is to give access to the user for a specific service by verifying his/her identity using his/her credentials like username and password. 

After IIS authentication, ASP.NET form authentication occurs. We can configure forms authentication by using forms element in web.config. The default attribute values for forms authentication are shown below,

<system.web>  
    <authenticationmode="Forms">  
        <formsloginUrl="Login.aspx" protection="All" timeout="30" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="default.aspx" cookieless="UseDeviceProfile" enableCrossAppRedirects="false" />  
        </authentication>  
</system.web>  

The FormsAuthentication class creates the authentication cookie automatically when SetAuthCookie() or RedirectFromLoginPage() methods are called. The value of an authentication cookie contains a string representation of the encrypted and signed FormsAuthenticationTicket object.

Validation Summary is used to display the list error messages of a page at fixed one place. If it summarises all the error messages of a page and shows them at once after the submit button is clicked and page is validated. 

MVC have provided the helper class display a summary of all validation errors of a page as:

@Html.ValidationSummary

To display validation summary we need to add this helper class in our view as:

@Html.ValidationSummary(false, "", new { @class = "text-danger" })

We can also display the custom error message using ValidationSummary. For this, we need to add the custom error messages to the ModelState in the respective action method.

Example:

if (ModelState.IsValid) { 
    bool nameExists = * check here *       
    if(nameExists)
    {
        ModelState.AddModelError(string.Empty, "Name already exists.");    
        return View(name);
    }}

A staple in Spring MVC interview questions with answers, be prepared to answer this one using your hands-on experience. This is also one of the top interview questions to ask an MVC.

RenderSection is used to designate a place to render content that is different from the one in RenderBody.

Example:

@RenderSection("footer", required: false)

By default, a section is required. We pass required: false to designate that section is optional.

@Section is used to render section in View as:

@section Footer

{
    <p>Section/Index page</p>
}

The high-level flow of the request with the following diagram:

Flow of the Request in MVC application

When the request is made by any client then at first it goes to the URL Routing, where the URL is compared to the routes that are present in the routing table. This helps to identify the controller and action method name. 

Based on the identified controller action method is called by passing the required parameters (if any). 

From where Model is called that interacts with Database to get the required response and returns to the controller action method.

The action method parses the response in the requested Action result format and returns back to View to present to the client.

Advanced

Unobtrusive javascript library allows to add validation to MVC views without any additional coding, only required to use attributes like RequiredAttribute, RangeAttribute and include the correct script files.

Example:

public class AddUserVM
{
   [DisplayName("First Name:")]
   [Required(ErrorMessage = "Please enter the first name.")]
   public string FirstName { get; set; }
   [DisplayName("Last Name:")]
   [Required(ErrorMessage = "Please enter the last name.")]
   public string LastName { get; set; }
   [DisplayName("Age:")]
   [Range(12, 120, ErrorMessage = "You must be between 12 and 120 years of age.")]
   public int Age { get; set; }
   [DisplayName("Email:")]
   [Required(ErrorMessage = "Please enter an email address.")]
   [EmailAddress(ErrorMessage = "Please enter a valid email address.")]
   public string EmailAddress { get; set; }
}

The above class setup is to handle the server side validations. Unobtrusive validations allow us to take existing validation attributes and use them at client-side to make the user experience much better.

Routing enables us to define a URL pattern that maps to the request handler.in asp.net request handler is .aspx file while in MVC request handler is controller and actions. All the route of the application is stored in RouteTable and the Routing engine helps in finding the appropriate handler class for the request, when the request and goes to the route table if it finds the appropriate  actions and controller and give the response and if it doesn`t find the controller and actions it will give the Error 404.

When we create the MVC application it creates one route by default which is defined under RouteConfig.cs file under AppStart Folder

Eg- public class RouteConfig

{
    Public static void RegisterRoutes(RouteCollection Routes)
{
routes,MapRoutes(name:”Deafult”,”
url : “{controller}/{actions}/{id}”,
deafults:new {controller=”Home”,action=”Index”,id=UrlParameter.Optional});
}
}

As we have seen in above that in Maproute() extension method of the route collection, where the name is default, URL pattern is “{controller}/{action}/{id}Defaults specify which controller, action method or value of id parameter should be used if not present in the incoming request URL. the main content of the URL is after the domain name localhost:1234/{controller}/{action}/{id}.

Where localhost:1234 is the domain name, if the URL doesn't contain anything after the domain then the default request i.e Home as  a controller and the Index as a view will handle the request

We can also configure a custom route using MapRoute extension method. We need to provide at least two parameters in MapRoute, route name, and a URL pattern. The Defaults parameter is optional.

Eg- public class RouteConfig

{
    Public static void RegisterRoutes(RouteCollection Routes)
{
routes,Map Routes(
name:”Default”,
url:”{controller}/{actions}/{id}”,
defaults:new {controller=”Home”,action=”Index”,id=UrlParameter.Optional});
routes,Map Routes(
name:”Students”,
url:”Students/{id}”,
defaults:new {controller=”Students”,action=”Index”l});
}
}

In the above example, there is a custom route where controller name is Students and since there is no such action defined in the URL so the default action is an index for all the actions belongs to the controller class.

When we want to be executed just prior to the action execution, when the user sends the request to the controller, in this the user create the custom class which works as a filter where the developer writes the logic which will be implemented just prior to the action execution, By programming method we can apply filters to the actions ,There are different type of filter use in MVC :

  1. Authorization: Authorization and authentication before executing the actions of the controller. built-in filter used is [Authorize], [RequireHttps], interface used is IAuthorizationFilter.
  2. Action Filters: it performs some action before and after the action methods execute before and after executing the action in the controller, there is no built-in filter used in this and interface used is IActionfilter.
  3. Result Filter: it basically performance some operation after and before the execution of view result. The build is filter used is [OutputCache].the interface used is IResultFilter.
  4. Exception filters: Performs some operation if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline. The built used is [HandleError] and the interface used is IExceptionFilter.

When there is any kind of exception in an application then the exception filter executes. HandleErrorAttribute ([HandlerError]) class is a built-in exception filter class in MVC framework. The HandleErrorAttribute class renders Error.cshtml which is inside the shared folder which is added by default during project creation when an unhandled exception occurs.

[HandleError]

public class HomeController : Controller
{
public ActionResult Index()
{
throw new Exception("This is unhandled exception");
return View();
}
public ActionResult About()
{ return View();
}
public ActionResult Contact()
{
return View();
}
}

A must-know for anyone looking for top MVC interview questions, this is one of the frequently asked MVC behavioral interview questions.

Html helper class helps when we want to show the property of the modal class into the view we use HTML helper class also when we want the values from the HTML input method parameter into the modal property we use HtmlHelper, HtmlHelper class generates HTML elements using the model class object in razor view.

Eg.

<p>
@Html.ActionLink(“Create New”,”Create”)
</p>

@Html is an object of HtmlHelper class. (We can  access a server-side object in razor syntax by using @ symbol).it is a property which is included in the base class of razor view WebViewPage. ActionLink() and DisplayNameFor() is extension methods included in HtmlHelper class, HTML is a property that we inherit from the ViewPage base class. So, it's available in all of our views and it returns an instance of a type called HTML Helper.

“HTML.BeginForm” writes an opening Form Tag. It also ensures that the method is going to be “Post” when the user clicks on the “Save” button.

Html.Beginform is very helpful as it helps us in changing the Url and helps us in changing the methods, The Html.LabelFor HTML Helper creates the labels on the screen. If we entered something wrong then it will display the error using Html.ValidationMessageFor .

There are lots of benefits:

It has overloaded methods to pre-populate the values (formatted, and safe for HTML) just like the ViewState.

It allows you to override the rendering by providing your own DLL for changing the rendering (a sort of "Controller Adapter" type methodology).

In ASP.NET MVC data Annotation are built in validation which  is applied on the modal class property and render it on the view in the validation summary

The DataAnnotations attributes included in System.ComponentModel.DataAnnotations namespace

Different types of data annotations are :

  1. Required
  2. String Length
  3. Range
  4. Regular Expression
  5. Credit Card
  6. Custom Validation
  7. Email Address
  8. File Extension
  9. Max Length
  10. Min Length
  11. Phone

Eg. 

public class Student

{
public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }
[Range(5,50)]
public int Age { get; set; }
}

In the above-stated example, we have the Required data annotation which implies that this field must be required in every scenario if the user left this modal property empty then it will give the default error message. In the same way, we can use the range to find the age property. This will validate and display an error message if the user has either not entered Age or entered an age less than 5 or more than 50.

Eg.

namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
public ActionResult Edit(int id)
{
var std = studentList.Where(s => s.StudentId == StudentId) .FirstOrDefault();
return View(std);
}
[HttpPost]
public ActionResult Edit(Student std)
{
if (ModelState.IsValid)
{ //write code to update student return RedirectToAction("Index"); }
return View(std);
}
}
}

In this Modal State will check whether the data is valid is true and it will update in the database and if not then it will return the same data in the Edit View

ModelState.IsValid determines that whether submitted values satisfy all the DataAnnotation validation attributes applied to model properties.

Eg  In the View the Data Annotation for the modal property will look like this

<div class="form-group">
@Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" })
</div>
</div>

The validation Summary helper method will display the error message, ValidationMessageFor is responsible to display an error message for the specified field.

Html.RenderPartial is directly written to the HTTP response stream which is used the same Text Writer object as used in the current webpage/template. Since there is no return type of Validation Annotations in MVC, the return type of Validation Annotations is void. We don't need to create any actions so it is simple to use, it is very useful when we want to show the data which is in another model view.

For example: if we want to show comments of an article, we will prefer to use RenderPartial method since the information and comments of the article are already populated in the view model.

@{Html.RenderPartial("_Comments");}

When it is executed its result is directly written to the response stream which makes it faster when compared with the partial method

In Html.Partial, the partial view is viewed as an encoded HTML string. Due to its string value return type, we can store the Html.Partial value in a variable.it same as Html.RenderPartial in case of action creation also,  we don’t need to create action, Partial method is also useful when the displaying data in the partial view is already in the corresponding view model which same as html.RenderPartial.

@Html.Partial("_Comments")

when we want a certain code to be used at some other view, we use a partial view. In simple words we can say that  it is a child view which can be used in some other views, it prevents the duplicate of code since it used the same partial view at some other places

When we want a partial view to be used on multiple controllers then we need to create a shared folder in the solution, otherwise, if it using in a single controller then it doesn`t need it. Using Partial() or RenderPartial() or RenderAction() helper method .we can render the partial view content in its parent view

@Html.Partial() helper method renders the specified partial view. It returns HTML string so we have a chance of modifying the HTML before rendering.

The different types of overloads used in partial views are:

  1. MvcHtmlString Html.Partial(string partialViewName)
  2. MvcHtmlString Html.Partial(string partialViewName,object model)
  3. MvcHtmlString Html.Partial(string partialViewName, ViewDataDictionary viewData)
  4. MvcHtmlString Html.Partial(string partialViewName,object model, ViewDataDictionary viewData)
  • MvcHtmlString Html.Partial(string partialViewName): it Renders the given partial view content in the referred view.
  • MvcHtmlString Html.Partial(string partialViewName, object model): in this, the modal passes its parameter into the partial view and render the view which is referred to it.
  • MvcHtmlString Html.Partial(string partialViewName, ViewDataDictionary viewData): it passes the view data dictionary to the partial view and render the partial view content in the preferred view.
  • MvcHtmlString Html.Partial(string partialViewName, object model, ViewDataDictionary viewData): when we want to pass the model object and view data dictionary to the partial view, and render the partial view content in the referred view.

when we want to improve the performance of the application we use output caching, it prevents the duplicate content to be loaded by caching the content returned by the controller,  when the controller methods are invoked, it is the best method to reduce the server round trips, reduces database server round trips, reduces network traffic etc.

Let’s Suppose when we want to display the list of records from the database in the view , so every time when the user invokes the controller method the query will be executed which will reduce the performance of the application, So, we can advantage of the "Output Caching" that avoids executing database queries each time the user invokes the controller method.

It is not necessary that the data will be retrieved until the time we have given, When memory resources become low, the cache starts evicting content automatically, and thus increase the performance of the Project.

The duration is in seconds by default the value used is 60 seconds

[HttpPost]  
   [OutputCache(Duration = 10, VaryByParam = "name")]  
   public ActionResult SearchCustomer(string name = "")  
   {
       NorthwindEntities db = new NorthwindEntities();  
       var model = from r in db.Customers  
                   where r.ContactName.Contains(name)  
                   select r;
       if (model.Count() > 0)  
       {
           return View(model);  
       }
       else
       {
           return View();  
       }
   }

In the above code the "name" parameter passed by the user and then, depending on the name, selecting matching records with a LINQ query and then checking if the model has the number of records greater than zero then send the model to the view else simply send the view (no model),VaryByParam="name" and "VeryByParam" is something that makes many differences

1.VaryByParam = "none": Think of it like, we don't want to care about the form parameter or query string parameter passed by the user from the view page. If I use "none" then it will create the same cached version of the content for every user who visits the website,

2.VaryByParam = "name": By using this we can create different cached versions of the content when the query string parameter is varied from one param to other. In other words if I find records matching "ce" string then a new cache will be created by replacing the older one, again if I find records matching "ab" string then a new cache will be created by replacing the last one ("ce" cached), no matter duration is elapsed or not.

Bundling and Modification is used to improve the request load time, In this, we can store many static files from the server in a single request, It is created in BundleConfig.cs in the App_Start folder, This file is creating Bundles by associating multiple files to routes. For example, the "~/bundles/bootstrap" route will correspond to both the bootstrap.js file and the respond.js file, and the browser will only need one HTTP request to retrieve both files

Eg.

using System. Web;
using System.Web.Optimization;

namespace BundlingExample
{
   public class BundleConfig
   {
       public static void RegisterBundles(BundleCollection bundles)
       {
           bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                       "~/Scripts/jquery-{version}.js"));

           bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                       "~/Scripts/modernizr-*"));

           bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                     "~/Scripts/bootstrap.js",
                     "~/Scripts/respond.js"));

           bundles.Add(new StyleBundle("~/Content/css").Include(
                     "~/Content/bootstrap.css",
                     "~/Content/site.css"));

           BundleTable.EnableOptimizations = false;
       }
   }
}
  • Minification : Minification is used to remove the white space, text, short comments from the files such as JavaScript and CSS files without expecting to alter functionality to reduce the size, which causes improved load times of a Webpage.

Eg.

sayHello = function(name)
{ //this is comment
var msg = "Hello" + name; alert(msg);
}
Minified Javascript is
sayHello=function(n){var t="Hello"+n;alert(t)}

it has removed unnecessary white space, comments and also shortening variable names to reduce the characters which in turn will reduce the size of JavaScript file., It increases the loading effects of a page by minimizing the number of request and size of the files.

There are different types of bundles used in MVC which is defined under the System.web.Optimization namespace

  • ScriptBundle: ScriptBundle is responsible for JavaScript minification of single or multiple script files.
  • StyleBundle: StyleBundle is responsible for CSS minification of single or multiple style sheet files.

DynamicFolderBundle: it represents a Bundle object that ASP.NET creates from a folder that contains files of the same type.

Bundling and Minification It Reduces the request and size of the js and css resource file and thereby improving the responsiveness of our apps.

Don't be surprised if this question pops up as one of the top MVC interview questions and answers for experienced professionals in your next interview.

MVC have separate folders for Model, View and Controller. In the case of large projects, it becomes unmanageable with the default MVC structure. MVC 2 has introduced Area.
The area allows partitioning of large applications into smaller units, where each unit contains a separate folder structure, which is as the default MVC structure.
For  Example, Large applications may have different modules like admin, HR etc. So Area can contain separate MVC folder structure for each module.

Create MVC Area

To add MVC Area into your application, follow the below steps:

  1. Right-click to project solution explorer -> Add -> Area
  2. Enter the name of the area in the dialogue box and click Add button
  3. An area with a given name gets added with separate MVC folder structure.

When we want to use a code for pre-installed web API and MVC, we use scaffolding  .it is a quite quick process which interacts with the data model. The main use of adding scaffolding is to interact with code and data model fast. It reduces the amount of time to develop standard data operations in your project.

Scaffold templates are used to generate code for basic CRUD operations and writes a method specific to each DML operation against your database with the help Entity Framework. For this, they use Visual Studio T4 templating system to generate views.

Let's understand it with an example.

Let's create a simple class by the name of Employee.cs.

Add some properties to Employee class using the following code

using System;

namespace MVCScaffoldingDemo.Models {
  public class Employee{
     public int ID { get; set; }
     public string Name { get; set; }
     public DateTime JoiningDate { get; set; }
     public int Age { get; set; }
  }
}

We need to add another class, which will communicate with Entity Framework to retrieve and save the data.

using System;
using System.Data.Entity;

namespace MVCScaffoldingDemo.Models{
  public class Employee{
     public int ID { get; set; }
     public string Name { get; set; }
     public DateTime JoiningDate { get; set; }
     public int Age { get; set; }
  }

  public class EmpDBContext : DbContext{
     public DbSet<Employee> Employees { get; set; }
  }
}

As we know that EmpDBContext which is derived from the DB.Context class, In this class, we have one property with the name DbSet, which basically represents the entity which you want to query and save.

Validation Summary is used to visualise the error message in the unordered list which is in ModelStateDictionary object.we can display the validation error of each property which is defined under modal

ValidationSummary() Signature

MvcHtmlString ValidateMessage(bool excludePropertyErrors, string message, Object htmlAttributes)

If we want to show error message summary of the field which is defined under the modal then specify excludePropertyErrors = false.

To display field error in the validation summary

Syntax is @Html.ValidationSummary(false, "", new { @class = "text-danger" })

We can also display a custom error message using ValidationSummary. If Student name exists in the database then it will display the message.

To display a custom error message, first of all, you need to add custom errors into the ModelState in the appropriate action method.

Eg.

if (ModelState.IsValid)
{
bool nameAlreadyExists = * check database *
if(nameAlreadyExists)
{
ModelState.AddModelError(string.Empty,
"Student Name already exists.");
return View(std);
}
}

In this Validation Summary will automatically generate the error message into the modal state

we have to add the custom error messages using the ModelState.AddModelError method

The Different Validation overloading methods are :

  • ValidationSummary(HtmlHelper, Boolean, String, Object): It Returns an unordered list of validation messages that are in the modelstatedictionary object and optionally displays only model-level errors.
  • ValidationSummary(HtmlHelper, Boolean, String, IDictionary<String,Object>): it will worked same as the ValidationSummary(HtmlHelper, Boolean, String, Object).
  • ValidationSummary(HtmlHelper, String, Object)
  • ValidationSummary(HtmlHelper, String, IDictionary<String,Object>)
  • ValidationSummary(HtmlHelper, Boolean, String)
  • ValidationSummary(HtmlHelper, String)
  • ValidationSummary(HtmlHelper, Boolean)
  • ValidationSummary(HtmlHelper)

Application life cycle is simply a series of steps or events used to handle some type of request or to change an application state.it uses the HTTP as a protocol to send the request on the browser, One thing that is true for all these platforms regardless of the technology is that understanding the processing pipeline can help you better leverage the features available and MVC is no different.

There are 2 different life cycle used in Asp.Net MVC:-

  1. Application Life Cycle
  2. Request Life Cycle

Application life cycle helps in getting to know that IIS will start working till its time will stop.

First, the request will find the routing method which is defined under the RouteConfig.cs, where there is a controller and its action method, is defined in the URL, after the controller has been created,actually begins running IIS until the time it stops,A component called the action invoker finds and selects an appropriate Action method to invoke the controller,MVC separates declaring the result from executing the result. If the result is a view type, the View Engine will be called and it's responsible for finding and rendering our view, If the result is not a view, the action result will execute on its own. It displays the actual HTTP result during the execution of the request.

This is a common yet one of the most important ASP.NET MVC interview questions and answers for experienced professionals, don't miss this one.

To make the development easy and simple as compared to asp.net web form application we use attribute routing, it is one of the different method which works differently routing

We used to define the routing in either Global.asax and RouteConfig.cs where this will decide which URL has to be chosen for the development

We need to put routes.MapMvcAttributeRoutes() in the routeconfig.cs which  enable attribute based routing on our MVC web application that can be done by only one line

Eg.

public static void RegisterRoutes(RouteCollection routes)

{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(  
name: "Default",  
url: "{controller}/{action}/{id}",
defaults: new { controller = "Product", action = "List", id =      UrlParameter.Optional }
);
}
In an action method, it is used like this
Eg.
[Route("products/{id?}")]
public ActionResult Details(string id)   
{
if (string.IsNullOrEmpty(id))
{
return View("List", GetProductList());
}
return View("Details", GetProductDetails());
}

Route Prefixes

We put the Route Prefix inside the controller which the request follow the route which is defined under the controller in the action method

Eg.

[RoutePrefix("products")]
public class ProductController : Controller
{
[Route]
public ActionResult List()
{
return View();
}
[Route("{id?}")]
public ActionResult Details(string id)
{
if (string.IsNullOrEmpty(id))  
{
return View("List");  
}
return View("Details");  
}
}

MVC routing uses the route table to look up and call the desired controller method, which renders the respected view. We can provide the routes in routeconfig file.

Sometimes it is required to have routes that are different from the ones configured in routeconfig and is specific to any controller or controller action method. In this attribute, routing comes into the picture.

To enable attribute based routing to add below line to routeconfig file under RegisterRoutes methods.

routes.MapMvcAttributeRoutes();

Samples of attribute routing:

  1. [Route(“products/{id?}”)]

    This route is to get a product with a given id. If id not provided then return all products

  1. [RoutePrefix(“products”)]

   This is places over the controller. All routes that start with products come to here

  1. [RouteArea(“business”)]

    RouteArea is a way to specify are in the route. It is just to let the route know that controller belongs to some area.

Description

MVC is a rich web application framework for building web apps and APIs using the Model-View-Controller design pattern. This is the 6th most popular framework in India and 10th most popular in top 1 Million sites in framework around the world. Today, ASP.Net MVC framework has occupied the web market replacing many competing frameworks with it. This has increased the demand for skilled MVC developers to create appealing, fast, and secure web applications. According to Neuvoo, the average ASP.Net MVC Developer salary in the USA is $110,000 per year or $56.41 per hour. Entry-level positions start at $70,000 per year while most experienced workers make up to $187,000 per year. An MVC Course can raise this number significantly.

Many companies like Innovecture LLC., eXcell, IntelliX Software, Inc., CyberCoders, Workbridge Associates, GemFind, etc. hire ASP.Net MVC skilled professionals. With this skill, an individual can play various roles like C# ASP.Net Developer, ASP.NET MVC Developer, ASP.Net/SQL Server Developer, Full-Stack Developer (GitHub, ASP.NET MVC), etc. in the organizations. If you are applying for the ASP.Net MVC developer/programmer job, it is good to prepare beforehand with these expert designed guide of .net MVC interview questions and answers for both experienced as well as freshers. These ASP.Net MVC interview questions and answers will definitely help you to crack your ASP.Net MVC interview successfully. You can take an advanced programming course to make the most of hands-on sessions on MVC concepts.

After going through these MVC interview questions and answers with top interview tips, you will be able to confidently face an interview and will boost your core interview skills that help you perform better. Prepare well and in time!

All the best! 

Read More
Levels