ASP.NET MVC Interview Questions



1) What do Model, View and Controller represent in an MVC application?

-MVC framework is a development method in which application is divided in three components: Model, View and Controller

-Model: In model we have to write our business logic and all the methods for data manipulations (CRUD)

-View: This component is responsible for user interface of the application.

-Controller: Controller handles the request and sends the response. It sends the request to View as a response or to Model. It acts as a mediator between Model and View.


2) What are the advantages of ASP.NET MVC framework?


-MVC framework is divided in model, view and controller which help to manage complex application. This way it divides the application in input logic, business logic and UI logic.

-MVC framework does not use view state or server-based forms which eliminate the problem of load time delays of HTML pages.

- MVC support ASP.NET routing which provide better URL mapping. In ASP.NET routing URL can be very useful for Search Engine Optimization (SEO) and Representation State Transfer (REST).

-MVC Framework support better development of test-driven development (TDD) application.

-In MVC Framework Testing becomes very easier. Individual UI test is also possible.



3)In which assembly is the MVC framework defined?
System.Web.Mvc

4) Is it possible to share a view across multiple controllers?

Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.


5) Can you explain the complete flow of MVC? 

Below are the steps how control flows in MVC (Model, view and controller) architecture:-
  • All end user requests are first sent to the controller.
  • The controller depending on the request decides which model to load. The controller loads the model and attaches the model with the appropriate view.
  • The final view is then attached with the model data and sent as a response to the end user on the browser.


6) Where is the route mapping code written?

The route mapping code is written in the “global.asax” file.

7) Can we map multiple URL’s to the same action?

Yes , you can , you just need to make two entries with different key names and specify the same controller and action.

8) How can we navigate from one view to other view using hyperlink?

By using “ActionLink” method as shown in the below code. The below code will create a simple URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.

<%= Html.ActionLink("Home","Gotohome") %>  

9) How can we restrict MVC actions to be invoked only by GET or POST?

We can decorate the MVC action by “HttpGet” or “HttpPost” attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the “DisplayCustomer” action can only be invoked by “HttpGet”. If we try to make Http post on “DisplayCustomer” it will throw an error.

[HttpGet]
        public ViewResult DisplayCustomer(int id)
        {
            Customer objCustomer = Customers[id];
            return View("DisplayCustomer",objCustomer);
        } 

 10) What is Routing in ASP.NET MVC?
 
In case of a typical ASP.NET application, incoming requests are mapped to physical files such as .aspx file. ASP.NET MVC framework uses friendly URLs that more easily describe user’s action but not mapped to physical files.

ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can define routing rules for the engine, so that it can map incoming request URLs to appropriate controller. 

Practically, when a user types a URL in a browser window for an ASP.NET MVC application and presses “go” button, routing engine uses routing rules that are defined in Global.asax file in order to parse the URL and find out the path of corresponding controller.
Routing helps you to define a URL structure and map the URL with the controller.
For instance let’s say we want that when any user types “http://localhost/View/ViewCustomer/”,  it goes to the  “Customer” Controller  and invokes “DisplayCustomer” action.  This is defined by adding an entry in to the “routes” collection using the “maproute” function. Below is the under lined code which shows how the URL structure and mapping with controller and action is defined.


routes.MapRoute(
               "View", // Route name
               "View/ViewCustomer/{id}", // URL with parameters
               new { controller = "Customer", action = "DisplayCustomer", 
id = UrlParameter.Optional }); // Parameter defaults   
 
 
 
 

 

11) How can we do validations in MVC? 

 
 
One of the easy ways of doing validation in MVC is by using data
annotations. Data annotations are nothing but attributes which you can be
applied on the model properties. For example in the below code snippet we have
a simple “customer” class with a property “customercode”.
 
 
 
This”CustomerCode” property is tagged with a “Required” data annotation attribute.
In other words if this model is not provided customer code it will not accept
the same.
 
 
 
 
public class Customer
 
{
 
        [Required(ErrorMessage="Customer code is required")]
 
        public string CustomerCode
 
        {
 
            set;
 
            get;
 
        } 
 
 
 
 
In order to display the validation error message we need to use
“ValidateMessageFor” method which belongs to the “Html” helper class.
 
 
 
 
 
<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
 
{ %>
 
<%=Html.TextBoxFor(m => m.CustomerCode)%>
 
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
 
<input type="submit" value="Submit customer data" />
 
<%}%> 
 
 
 
Later in the controller we can check if the model is proper or not by using
“ModelState.IsValid” property and accordingly we can take actions. 
 
 
 
 
public ActionResult PostCustomer(Customer obj)
 
{
 
if (ModelState.IsValid)
 
{
 
                obj.Save();
 
                return View("Thanks");
 
}
 
else
 
{
 
                return View("Customer");
 
}
 
 
 
 

 

12) Can we display all errors in one go?

 
Yes we can, use “ValidationSummary” method from HTML helper class.
 
 
 
13) What is the difference between ViewData, ViewBag and TempData?
 
 
 

In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework provides different options i.e. ViewData, ViewBag and TempData.

Both ViewBag and ViewData are used to to communicate between controller and corresponding view.But this communication is only for server call, it becomes null if redirect occurs. So, in short, its a mechanism to maintain state between controller and corresponding view.

ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). viewData being a dictionary object is accessible using strings as keys and also requires typecasting for complex types.On the other hand, ViewBag doesn't have typecasting and null checks.

TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be used to maintain data between redirects i.e from one controller to the other controller.

 
 
 
 
 
 
 
 
 

14) How can we enable data annotation validation on client side?

It’s a two-step process first reference the necessary jquery files.

<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script> 
Second step is to call “EnableClientValidation” method.

<% Html.EnableClientValidation(); %> 
 


 
15) What are Action Filters in ASP.NET MVC?
 
 
If we need to apply some specific logic before or after action methods, 
we use action filters. We can apply these action filters to a controller
or a specific controller action. Action filters are basically custom 
classes that provide a mean for adding pre-action or post-action 
behavior to controller actions.
 
 
·         Authorize filter can be used to restrict access to a specific user or a role.
 
·         OutputCache filter can cache the output of a controller action for a specific duration.
 
 
 

 

16) What are the different types of results in MVC?

 
There 12 kinds of results in MVC, at the top is “ActionResult”class which is
a base class that canhave11subtypes’sas listed below: -
 
 
 
1.  ViewResult
2.       - Renders a specified view to the response stream
 
3.  PartialViewResult
4.       - Renders a specified partial view to the response stream
 
5.  EmptyResult
6.       - An empty response is returned
 
7.  RedirectResult
8.       - Performs an HTTP redirection to a specified URL
 
9.  RedirectToRouteResult
10.     - Performs an HTTP redirection to a URL that is determined by the routing
11.     engine, based on given route data
 
12.JsonResult
13.     - Serializes a given ViewData object to JSON format
 
14.JavaScriptResult
15.     - Returns a piece of JavaScript code that can be executed on the client
 
16.ContentResult
17.     - Writes content to the response stream without requiring a view
 
18.FileContentResult
19.     - Returns a file to the client
 
20.FileStreamResult
21.     - Returns a file to the client, which is provided by a Stream
 
22.FilePathResult
23.     - Returns a file to the client
 
 
 

 

17) What is a HTML helper?

 
A HTML helper is a method that returns string; return string usually is the HTML tag. The standard HTML
helpers (e.g. Html.BeginForm(),Html.TextBox()) available in MVC are lightweight as it does not rely on event model or view state as that of in ASP.Net server
controls. 
 
18) What is ASP.NET Web API?
 
 ASP.NET Web API is a framework for building and consuming 
HTTP Services. It supports wide range of clients including browsers and 
mobile devices. It is a great platform for developing RESTful services 
since it talks HTTP.

19) What is the use of Display Modes?

View can be changed automatically based on browser(For mobile and desktop browser’s) Display Modes is newly added feature in ASP.NET MVC 4. Views selected automatically by application depending on the browser. Example: If a desktop browser requests login page of an application it will return Views\Account\Login.cshtml view & if a mobile browser requests home page it will return Views\Account\Login.mobile.cshtml view.

 
 
20)  What are the main features of ASP.NET MVC 4 used by ASP.NET Web API?
  • Routing changes: ASP.NET Web API uses same convention for config mapping that ASP.NET MVC provides.
  • Model Binding & Validation: ASP.NET Web API uses same model binding functionality, but HTTP specific context related operations only.
  • Filters: The ASP.NET Web API uses most of built-in filters from MVC.
  • Unit Testing: Now Unit testing based on MVC, strongly unit testable.
21)  What are Bundling & Minification features in ASP.NET MVC 4?

 Bundling & Minification reduces number of HTTP requests. Bundling & Minification combines individual files into single. Bundled file for CSS & scripts and then it reduce’s overall size by minifying the contents of the bundle.

No comments:

Post a Comment