22 March 2015

MVC Interview Question in Dotnet

MVC Interview Question in Dotnet

1.     What is MVC ?
MVC is an architectural pattern which separates the representation and user interaction.
M - Model -  Application business logic is in the Model
V - View - Views represent the user interface, with which the end users interact.
C - Controller - Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface.

2. Advantages of MVC
1.     ASP.NET MVC views are light weight, as they do not use viewstate.
2.     Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
3.     Complex application can be easily managed by the developer.
4.     In Razor view engine using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks.
5.     Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.). Bundling that makes it easy to combine or bundle multiple files into a single file.
6.     Minification performs a variety of different code optimizations to scripts or css, such as removing unnecessary whitespace and comments and shortening variable names to one character.
3. MVC Application Life cycle
MVC application life cycle has two main phases
Creating the request object and sending our response to the browser.
Creating the request Object
Step 1: Fill route : - MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.
Step 2: Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.
Step 3 Request context created: - The “RouteData” object is used to create the “RequestContext” object.
Step 4 Controller instance created: - This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.
Creating Response object: - This phase has two steps executing the action and finally sending the response as a result to the view.

4.Routing in MVC
Routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. At runtime, Routing engine use the Route table for matching the incoming request's URL pattern against the URL patterns defined in the Route table. You can register one or more URL patterns to the Route table at Application_Start event.

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

The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application start event.

5.HTML helpers in MVC
HTML helpers help you to render HTML controls in the view. For instance if you want to display a HTML textbox on the view , below is the HTML helper code.
Copy Code

<%= Html.TextBox("LastName") %>
6. Difference between HTML.TextBoxFor and HTML.TextBox
Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t
Html.TextBoxFor(m => m.CustomerCode)

7.Attribute based routing in MVC
This is a feature introduced in MVC 5. By using the "Route" attribute we can define the URL structure.
public class HomeController : Controller
       public ActionResult GotoAbout()
           return View();
Most of the time developers code in the action methods. Developers can see the URL structure right upfront rather than going to the “routeconfig.cs” and see the lengthy codes.

8. Navigate from one view to another using a hyperlink?
<%= Html.ActionLink("Home","Gotohome") %>
Home - Controller
Gotohome - Action

9. Restrict MVC actions to be invoked only by GET or POST
We can decorate the MVC action with the 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.

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

10.ViewData, ViewBag and TempData

ASP.NET MVC offers us three options ViewData, ViewBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility.
Helps to maintain data when you move from controller to view.
ViewData requires typecasting for complex data type and check for null values to avoid error and ViewBag doesn’t require typecasting for complex data type.
ViewBag & ViewData Example:

public ActionResult Index()
                ViewBag.Name = "Arun Prakash";
                return View();   

public ActionResult Index() 
                ViewData["Name"] = "Arun Prakash";
                return View();

In View, we call like below:


Helps to maintain data when you move from one controller to another controller or from one action to other action. In other words when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables. TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only.

It requires typecasting for complex data type and check for null values to avoid error.
So if “TempData” is once read it will not be available in the subsequent request.

11.Partial views in MVC?
Partial view is a reusable view (like a user control) which can be embedded inside other view.

12.Validations in MVC?
Data annotations are nothing but attributes which can be applied on model properties.

[StringLength(50, MinimumLength = 2)]
[Range(15, 100)]

Data type
The data type annotation can be used to specify the data type for validation. The information may also be used as UI hint later in rendering process.
Copy Code

public string url { get; set; }
public string phone { get; set; }
public DateTime updatedate { get; set; }

public string phone { get; set; }
public class Customer
    [Required(ErrorMessage="Customer code is required")]
    public string CustomerCode

<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>

Later in the controller we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take actions.

public ActionResult PostCustomer(Customer obj)
    if (ModelState.IsValid)
        return View("Thanks");
        return View("Customer");

13.Can we display all errors in one go?
Yes, we can; use the ValidationSummary method from the Html helper class.
<%= Html.ValidationSummary() %>

14. Ajax in MVC

Implement Ajax using Ajax libraries
function GetData()
                var url = "/MyAjax/getCustomer";
                $.post(url, function (data)
implement AJAX by using the “AJAX” helper library

   var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};                    
<% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>

<%} %>

15.Difference between ActionResult and ViewResult?

ActionResult is an abstract class while ViewResult derives from the ActionResult class.
ActionResult has several derived classes like ViewResult, JsonResult, FileStreamResult, and so on.
Depending on the flag (IsHtmlView) it will either return a ViewResult or JsonResult.

public ActionResult DynamicView()
   if (IsHtmlView)
                return View(); // returns simple ViewResult
                return Json(); // returns JsonResult view

16.Different types of results in MVC?

There 12 kinds of results in MVC, at the top is the ActionResult class which is a base class that can have 11 subtypes as listed below:

                1.ViewResult - Renders a specified view to the response stream
                2.PartialViewResult - Renders a specified partial view to the response stream
                3.EmptyResult - An empty response is returned
                4.RedirectResult - Performs an HTTP redirection to a specified URL
                5.RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine,  based on given route data
                6.JsonResult - Serializes a given ViewData object to JSON format
                7.JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
                8.ContentResult - Writes content to the response stream without requiring a view
                9.FileContentResult - Returns a file to the client
                10.FileStreamResult - Returns a file to the client, which is provided by a Stream
                11.FilePathResult - Returns a file to the client

17. Areas in MVC?
Group the  controller classes into logical section
18. MVC Scaffolding
Scaffolding is a technique in which the MVC template helps to auto-generate CRUD code. CRUD stands for create, read, update and delete.
19.Multiple Submit buttons pointing to multiple actions in a single MVC view

Ajax Way

20. MVC Ajax Example
//MVC JQuery Ajax


  data : {
          data1: data1,
          data2: data2,


  success : function(result){
  error : function(){
20. MVC Action Filters
ASP.NET MVC provides Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.

Authorization filter, which makes security decisions about whether to execute an action method, such as performing authentication or validating properties of the request.

Action filter, which wraps the action method execution. This filter can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method

OnActionExecuting - Runs before execution of Action method.
OnActionExecuted - Runs after execution of Action method.
OnResultExecuting - Runs before content is rendered to View.
OnResultExecuted - Runs after content is rendered to view.

Result filter, which wraps execution of the ActionResult object. This filter can perform additional processing of the result, such as modifying the HTTP response.

Exception filter, which executes if there is an unhandled exception thrown somewhere in action method, starting with the authorization filters and ending with the execution of the result. Exception filters can be used for tasks such as logging or displaying an error page.

21. MVC Custom Filters
When you request any page into MVC Application, it will go through the Routing Architecture. Your Routing system will decide your URL pattern. The default routing algorithm is like {controller}/ {action}/ {id} patterns. But it can be possible to change that pattern using Custom Routes.

When you create a Custom Route, you can also include route constraints. These constraints are used to restrict the requests to match routes. There are three basic types of constraints:

1.     Regular Expression Constraints - check the pattern of the Route and prevent invalid requests
2.     HttpMethod Constraints - You can match route with any type of the HTTP operation like POST, GET, etc. you want to prevent user to access particular URL when GET operation occurs but not POST operation occurs.
//Custom Route With HttpMethod Constraint
                new { Controller = "Blog", action = "Insert" },
        new { method = new HttpMethodConstraint("GET") });

 3. CatchAllRoutes- Suitable for the dynamic URL, But if you want to match your URL, regardless of the number     of the segments for that, we have to create Catch-All Parameter.

22.Action Results - ActionResult method works as a return type of any controller method in the MVC. It acts like the base class of Result classes. It is used to return the models to the Views, file streams and also redirect to the controllers.
23.Razor View Engine VS Web Form(ASPX) View Engine

1.     Razor Engine is an advanced view engine that was introduced with MVC3.
Web Form Engine is the default view engine for the Asp.net MVC that is included with Asp.net MVC from the beginning.

             2. The file extensions used with Razor Engine are different from Web Form Engine. It has .cshtml (Razor
            with  C#) or .vbhtml (Razor with VB) extension for views, partial views, editor templates and for layout pages.

3. The file extensions used with Web Form Engine are also like Asp.net Web Forms. It has .aspx         extension     for  views, .ascx extension for partial views & editor templates and .master extension for layout/master pages.

               4. Razor has new and advance syntax that are compact, expressive and reduces typing.
               Web Form Engine has the same syntax like Asp.net Web Forms uses for .aspx pages.

5. Razor syntax are easy to learn and much clean than Web Form syntax. Razor uses @ symbol to make the code like as:
@Html.ActionLink("SignUp", "SignUp")
Web Form syntax are borrowed from Asp.net Web Forms syntax that are mixed with html and sometimes make a view messy. Webform uses <% and %> delimiters to make the code like as:
<%: Html.ActionLink("SignUp", "SignUp") %>

6.By default, Razor Engine prevents XSS attacks(Cross-Site Scripting Attacks) means it encodes the script or html tags like <,> before rendering to view.
Web Form Engine does not prevent XSS attacks means any script saved in the database will be fired while rendering the page

7. Razor Engine is little bit slow as compared to Webform Engine.
Web Form Engine is faster than Razor Engine.

8. Razor Engine, doesn't support design mode in visual studio means you cannot see your page look and feel.
Web Form engine support design mode in visual studio means you can see your page look and feel without running the application.

9. Razor Engine support TDD (Test Driven Development) since it is not depend on System.Web.UI.Page class.
Web Form Engine doesn't support TDD (Test Driven Development) since it depend on System.Web.UI.Page class which makes the testing complex.


  1. I think this is an great blogs. Such a very informative and creative contents. These concept is good for these knowledge.I like it and help me to development very well.Thank you for this brief explanations.
    Dot Net Training in Chennai

  2. This comment has been removed by the author.


Comments Welcome