The ASP.NET MVC framework is one of the most popular frameworks for developing web applications. If you have been working in .NET and developing web-based applications, then there is a good chance that you have already used ASP.NET MVC in your projects. There is a high demand for good ASP.NET MVC developers with knowledge and experience in .NET and ASP.NET MVC. One way to prepare yourself for such job interviews is to look for potential interview questions. These are some MVC interview questions I have faced during MVC interviews:-
Answer: MVC Stands For Model, View, Controller.MVC is an architectural pattern that separates an application into three Interconnected parts: Model, View, and Controller.
Model: It is used to represent application data.
View: It is used to represent user interface
Controller: It is used to handle the request sent by the user's and return an output response according to the user's requests through View.
Answer: Following are features added newly:-
Answer: Below is the process followed in the sequence:
Answer: The MVC framework is defined in System.Web.Mvc.
Answer: There are 9 return types we can use to return results from a controller to view as given below:-
Answer: In ASP.NET MVC, many times we would like to perform some actions before or after the action method gets executed. For achieving this functionality,ASP.NET MVC provides a feature to add pre or post-action behavior on the controllers action method.
Answer: ASP.NET MVC framework supports the following action filters:
Answer: An action filter is an attribute that you can apply to a controller action or an entire controller that modifies the way in which the action is executed. These attributes are special .NET classes derived from System. An attribute that can be attached to classes, methods, properties, and fields. The ASP.NET MVC framework includes several action filters -
Output Cache: This action filter caches the output of a controller action for a specified amount of time.
Answer: In ASP.NET MVC, HTML helpers are much like traditional ASP.NET Web Form controls. 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.
In Short, HTML helpers help you to render HTML controls in the view Programmatically. For Example, if you want to display an HTML textbox on the view, below is the HTML Helper code
@Html.TextBox("txt_Name")
For the checkbox below is the HTML helper code. In this way, we have HTML helper methods for every HTML control that exists.
@Html.CheckBox("Yes")
Answer:
Bundling: Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript, and other bundles. Fewer files mean fewer HTTP requests and that can improve first-page load performance.
Minification: Minification performs a variety of different code optimizations to scripts or CSS, such as removing unnecessary white space and comments and shortening variable names to one character.
Answer: In ASP.NET MVC, Routing is a pattern matching mechanism that is responsible for mapping incoming browser request to particular MVC controller action method.
Answer: The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application start event.
Answer: Yes, you can, you just need to make two entries with different key names and specify the same controller and action.
Answer: Attribute-based Routing is yet another new feature in MVC 5, in this feature you can apply route attribute on Controller and Action such that it influences the selection of Controller and Action Method.
Attribute-based Routing is totally different from traditional routing in traditional routing we declare route in RouteConfig.cs file.
public class HomeController : Controller
{
// eg: /home
[Route(“home”)]
public ActionResult Index() { … }
// eg: /article/5
[Route(“article/{PostId}”)]
public ActionResult Show(int PostId) { … }
// eg: /article/5/edit
[Route(“article/{PostId}/edit”)]
public ActionResult Edit(int PostId) { … }
}
Answer: To enable attribute routing, call MapMvcAttributeRoutes during configuration.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapMvcAttributeRoutes();
}
}
Answer: Below are the important namespaces used in ASP.NET MVC :
Answer:
public ActionResult Index()
{
ViewBag.Name = "TutorialsRack.com";
return View();
}
ViewDataDictionary
class and is accessible using strings as keys.public ActionResult Index()
{
ViewData["Name"] = "TutorialsRack.com";
return View();
}
@ViewBag.Name
@ViewData["Name"]
Answer: TempData is a dictionary which is derived from the TempDataDictionary class. TempData can be used to store temporary data which can be used in the subsequent request. TempData will be cleared out after the completion of a subsequent request.
In Other Words, TempData is used to passing data from one controller to another controller or one action to other action. TempData internally uses Session variables. TempData is used to pass data from one request to the next request.
Answer: 3 different ways to deal with session management in ASP.NET MVC:-
TempData, ViewBag, and ViewData.
Answer: In ASP.NET MVC, a partial view is similar to user control in ASP.NET Web form. Partial view is a reusable view, which can be used as a child view in multiple other views OR you can say, a partial view is a chunk of HTML that can be safely inserted into an existing View. It eliminates duplicate coding by reusing the same partial view in multiple places. You can use the partial view in the layout view, as well as other content views.
Answer: Layout pages are similar to master pages in traditional ASP.NET Web Forms. This is used to set the common look across multiple pages. In each child page we can find :
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
This indicates child page uses TestLayout page as it's a master page.
Answer: Section is the part of HTML which is to be rendered in the layout page. In 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{
Test Content
}
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)
Renderbody()
And Renderpage()
in ASP.NET MVC?Answer: Renderbody: In ASP.NET MVC, RenderBody method is very similar to ContentPlaceholder in ASP.NET WebForm. It Resides in the Layout page(or you can say Master page). There can only be one RenderBody method per Layout page.
@RenderBody()
RenderPage:- RenderPage method also exists in the Layout page to render another page exists in your application. A layout page can have multiple RenderPage methods.
@RenderPage("~/Views/Shared/_Header.cshtml")
Answer: This page is used to make sure the common layout page will be used for multiple views. Code written in this file will be executed first when the application is being loaded.
Answer: "ActionName" attribute can be used for changing the action name.
[ActionName("TestActionNew")]
public ActionResult TestAction()
{
return View();
}
So in the above code snippet "TestAction" is the original action name and in "ActionName" attribute, name - "TestActionNew" is given. So the caller of this action method will use the name "TestActionNew" to call this action.
Answer: Unlike code expressions that are evaluated and sent to the response, it is the blocks of code that are executed. This is useful for declaring variables which we may be required to be used later.
@{
int x = 12000;
string y = "John Doe";
}
Answer: Yes, we can share a view 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.
Answer: Name: This is the name of the route.
URL Pattern: Placeholders will be given to match the request URL pattern.
Defaults: When loading the application which controller, action to be loaded along with the parameter.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
)
}
{resource}.axd/{*pathinfo}
" in routing in ASP.NET MVC?Answer: Using this default route - {resource}.axd/{*pathInfo}
, we can prevent the requests for the web resources files like - WebResource.axd or ScriptResource.axd from passing to a controller.
Answer: Following are the rules for main Razor Syntax:
Answer: Benefits of Area in ASP.NET MVC:
Answer: Yes. We can use the razor code in javascript in cshtml by using element.
<script type="text/javascript">
@foreach (var item in Model) {
<text>
//javascript goes here which uses the server values
<text>
}
</script>
Answer: Below is the code snippet to return a string from an action method :
public ActionResult TestAction() {
return Content("Hello Test !!");
}
Answer: Below is the code snippet to return a string from action method :
public ActionResult TestAction() {
return JSON(new { prop1 = "Test1", prop2 = "Test2" });
}
Answer: AJAX Helpers are used to creating AJAX-enabled elements like as Ajax-enabled forms and links which performs the request asynchronously and these are extension methods of AJAXHelper class which exists in the namespace - System.Web.ASP.Net MVC
.
Answer: Below is the options in AJAX helpers :
Answer: "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.
Answer: View Model is a plain class with properties, which is used to bind it to strongly typed view. View Model can have the validation rules defined for its properties using data annotations.
Answer: By using "ActionLink" method as shown in the below code. The below code will make a simple URL which helps to navigate to the "Home" controller and invoke the "GotoHome" action.
@Html.ActionLink("Home", "Gotohome")
Answer: If you decorated action method with [NonAction] attribute you can't access that through URL. We can restrict this by using private also, but in some scenarios, we need public access so by declaringing with [NonAction] attribute we can prevent.
Answer: For razor views, the file extensions are
.cshtml: If C# is the programming language
.vbhtml: If VB is the programming language
Answer: Two methods for adding constraints to the route is
Answer: Razor is clean, lightweight, and syntaxes are easy as compared to ASPX.
<%=DateTime.Now%>
In Razor, it’s just one line of code:
@DateTime.Now
Answer: As per Microsoft, Razor is more preferred because it’s lightweight and has simple syntaxes.
Answer: For Windows authentication, you need to modify the web.config file and set the authentication mode to Windows.
<authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
Then in the controller or on the action, you can use the Authorize attribute which specifies which users have access to these controllers and actions. Below is the code snippet for that. Now only the users specified in the controller and action can access it.
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
//
// GET: /Start/
[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
public ActionResult Index()
{
return View("MyView");
}
}
Answer:
public ActionResult DynamicView()
{
if (IsHtmlView)
return View(); // returns simple ViewResult
else
return Json(); // returns JsonResult view
}
Answer:
Answer: To detect if the call on the controller is a POST action or a GET action we can use the Request.HttpMethod
property as shown in the below code snippet.
public ActionResult SomeAction()
{
if (Request.HttpMethod == "POST")
{
return View("SomePage");
}
else
{
return View("SomeOtherPage");
}
}
Answer: If you are in a debug mode you need to set EnableOptimizations to true in the bundleconfig.cs file or else you will not see the bundling effect in the page requests.
BundleTable.EnableOptimizations = true;
Answer: There are several benefits of using ASP.NET MVC are given below:
Answer: The main advantages of ASP.NET MVC are:
HTML.TextBox
" vs "HTML.TextBoxFor
"?Answer: Both of them provide the same HTML output, “HTML.TextBoxFor
” is strongly typed while "HTML.TextBox
" isn’t.
Below is a simple HTML code which just creates a simple textbox with "CustomerCode" as a name.
@Html.TextBox("CustomerCode")
Below is "Html.TextBoxFor" code which creates HTML textbox using the property name "CustomerCode" from object "m".
@Html.TextBoxFor(m => m.CustomerCode)
Answer: TempData is used to preserve the data for the next request, i.e. Once the data is read by the view it's lost, and not available for the next subsequent request. The data can be retained & preserved for the next subsequent request by using Keep() and Peek(), even if its read by a view.
And the main difference between keep() and peek is:
Keep: If we read “TempData” in the current request and we can keep method to persist TempData for the next request. In MVC, we are having void keep() and void keep(string key) methods to persist the data.
@TempData["key"];
TempData.Keep("key");
Peek: If you set a TempData in your action method and if you read it in your view by calling the "Peek" method then TempData will be persisted and will be available in next request
string msg = TempData.Peek("msg").ToString();
Answer: It uses Entity framework internally.
Answer: In ASP.NET MVC 2.0, Microsoft provided a new feature in MVC applications, Areas. Areas are just a way to divide or "isolate" the modules of large applications in multiple or separated MVC. When you add an area to a project, a route for the area is defined in an AreaRegistration file. The route sends requests to the area based on the request URL. To register routes for areas, you add code to the Global.asax file that can automatically find the area routes in the AreaRegistration file.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
}
Answer: Scaffolding is a technique used by ASP.NET MVC frameworks( and many other MVC Frameworks like ASP.NET MVC, Ruby on Rails, Cake PHP and Node.JS etc.,) to generate code for basic CRUD (create, read, update, and delete) operations against your database effectively.
Answer: The main purpose of using Output Caching is to dramatically improve the performance of an ASP.NET MVC Application. It enables us to cache the content returned by any controller method so that the same content does not need to be generated each time the same controller method is invoked. Output Caching has huge advantages, such as it reduces server round trips, reduces database server round trips, reduces network traffic etc.
Answer: Benefits of Area in MVC:
Answer: To create reusable widgets child actions are used and this will be embedded into the parent views. In ASP.Net MVC Partial views are used to have reusability in the application. Child action mainly returns partial views.
Answer: "ChildActionOnly" attribute is decorated over action methods to indicate that action method is a child action. Below is the code snippet used to denote the child action :
[ChildActionOnly]
public ActionResult MenuBar()
{
//Logic here
return PartialView();
}
Answer: MVC 6 is the latest version which is also termed as ASP VNEXT.
Comments