Friday, July 5, 2019

ASP.NET MVC Interview Questions

1. What is MVC?

Answer: 

MVC stands for Model, View, and Controller. MVC is a software architectural pattern which separates the representation and user interaction.

Model represents the real world object and provides data to the view. It is nothing but a set of classes that describes business logic.

View is responsible for look and feel. It represents UI components like HTML, CSS, jQuery etc.

Controller is responsible for taking the end user request via View and loading the appropriate Model and View.

2. How Model, View, Controller communicate each other in ASP.Net MVC?

Answer:

User interacts with the controller.

There is one-to-many relationship between Controller and View which means one controller can mapped to multiple views.

Controller and View can have a reference to model.

Controller and View can talk to each other.

Model and View cannot talk to each other directly. They communicate to each other with the help of controller.


3. What are the advantages of ASP.Net MVC over ASP.Net web form?

Answer:

There are following advantages of using ASP.NET MVC over ASP.NET web form.

i. The MVC framework provides a clean separation of the UI, Business Logic, Data or model.

ii. Automated UI testing is possible because now the behind code (UI interaction code) has moved to a simple .NET class. This gives us opportunity to write unit tests and automate manual testing.

iii. The ASP.NET MVC provides the better control over HTML, CSS and JavaScript than the traditional web form.

iv. The ASP.NET MVC is lightweight because it doesn’t use viewstate and thus reduces the bandwidth of the request.

v. The ASP.NET MVC is supported most of the feature of ASP.NET web form like authentication and authorization, roles, caching, session etc.

4. Explain the difference between 3-layer architecture and MVC architecture.

Answer:

MVC is an evolution of a three layered traditional architecture. Many components of the three layered architecture are the part of MVC.

A fundamental rule in three tier architecture is the client tier never communicate directly with the data tier. In a three-tier model all communication must pass through the middle tier.

MVC architecture is triangular. The view sends updates to the controller, the controller updates the model, and the view gets updated directly from the model.

5. Explain the MVC application life cycle.

Answer: 

Any web application first understands the request and depending on type of request, it sends out appropriate response. MVC application life cycle is not different, it has two main phases, first creating the request object and second sending our response to the browser.
The request object creation has four major steps,

Step 1: Fill route
Every MVC request is mapped to route table which specifies which controller and action to be invoked. If it is the first request, it fills the route table with route collection. This filling of route table happens in the global.asax file.

Step 2: Fetch route
Depending on the URL sent "UrlRoutingModule" searches the route table to create "RouteData" object. RouteData 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
The coming request object is sent to "MvcHandler" instance to create the object of controller class. 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.

6. What are the different return types of controller action methods?

Answer:

There are total nine return types to return results from controller to view. The base type of all these result types is ActionResult. 

1. ViewResult (View): It is used to return a webpage from an action method.

2. PartialviewResult (Partialview): It is used to send a part of a view which will be rendered in another view.

3. RedirectResult (Redirect): This return type is used to Redirects to another action method by using its URL.

4. RedirectToRouteResult (RedirectToAction, RedirectToRoute): It is used to Redirects to another action method.

5. ContentResult (Content): It returns a user defined content type. 

6. JsonResult (Json): This return type is used to return a serialized JSON object.

7. JavaScriptResult(JavaScript): This return type is used to return JavaScript code that will run in browser.

8. FileResult(File): This return type is used to returns binary output to write to the response.

9. EmptyResult(): This return type is used to represent a return value that is used if the action method must return a null result (void).


7. What is Routing in ASP.NET MVC?

Answer:

The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions. Routing is a pattern matching system that monitors the incoming request and figures out what to do with that request.

Routing helps us to define a URL structure and map the URL with the controller.

Below is the code which shows how the URL structure, mapping with controller and action is defined.

public static void RegisterRoutes(RouteCollection routes)
{
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );
}
protected void Application_Start()
{
        RegisterRoutes(RouteTable.Routes);
}

8. Explain attributes based routing in MVC. How to define it?

Answer:

This feature introduces in MVC 5. By using the "Route" attribute we can define URL structure. Attribute routing provides you more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API.

For example in the below code we have decorated the "GotoContact" action with the route attribute. The route attribute says that the "GotoContact" can be invoked using the URL structure "Users/contact".

public class HomeController : Controller
{
       [Route("Users/contact")]
       public ActionResult GotoContact()
       {
           return View();
       }
}

9. How to enable attribute routing in ASP.NET MVC?

Answer:

To enable attribute routing in ASP.NET MVC5 application, we just add a call to routes.MapMvcAttributeRoutes() method within RegisterRoutes() method of RouteConfig.cs file.

public class RouteConfig
{
        public static void RegisterRoutes(RouteCollection routes)
        {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
                //enabling attribute routing
                routes.MapMvcAttributeRoutes();
        }
}



10. What is the difference between Routing and URL rewriting?

Answer:

Routing is focused on mapping a URL to a resource while URL rewriting is focused on mapping one URL (new URL) to another URL (old URL).

URL rewriting rewrites your old URL to new one while routing never rewrites your old URL to new one but it maps to the original route.

11. How can we maintain session in MVC?

Answer:

Sessions can be maintained in MVC by three ways:
  • TempData
  • ViewData
  • ViewBag

12. What is the difference between ViewData, ViewBag and TempData?

Answer:

ViewData: 
ViewData helps to maintain data when we move from controller to view. It is derived from the ViewDataDictionary class. It is available for the current request only and also requires typecasting for complex data.

ViewBag:
It also helps to maintain data when we move from controller to view. It uses dynamic keyword internally. It is also available for the current request only and typecasting is not required.

TempData:
It is derived from TempDataDictionary class. Tempdata helps to maintain data when we move from one controller to another controller or from one action to another action. It requires typecasting for complex data.


13. What is Partial View in ASP.NET MVC?

Answer:

Partial view is a reusable view (like user control). A partial view is a view that is rendered within another view which means it can be embedded inside other view.

Partial view can be rendered using Html.Partial(), Html.RenderPartial(), Html.RenderAction() method. 

14. Explain the difference between View and Partial View?

Answer:

View:
  • View contains the layout page.
  • Before any view is rendered, viewstart page is rendered.
  • It is not lightweight as compare to Partial View.
  • View might have markup tag like html, head, title, body etc.
Partial View:
  • Partial view does not contain layout page.
  • We can pass regular view to the render partial method.
  • Partial view is designed specially to render within the view and just because of that it does not consist any mark up.
  • Partial View is lightweight compared to View.
  • Partial view can be embedded inside another view.

15 What are the HTML helpers in ASP.NET MVC?

Answer:

Html helpers are a method that returns a HTML string. HTML helpers help us to render HTML controls in the view. HTML helper does not have an event model and a view state.

We can also create our own HTML Helpers to render more complex content.

There are three types of HTML helpers. 

i. Inline HTML helpers

ii. Built-in HTML helpers
  • Standard HTML helpers
  • Strongly type HTML helpers
  • Templated HTML Helpers
iii. Custom HTML helper

If we want to add HTML textbox on view, below is the HTML helper.
<%= Html.TextBox("Name") %>

16. What is the difference between "HTML.TextBox" and "HTML.TextBoxFor"?

Answer:

HTML.TextBoxFor is strongly type while HTML.TextBox is not, but they both produce same HTML.

1:  @Html.TextBox("Name")
2: Html.TextBoxFor(m => m.Name)

will both produce
<input id="Name" name="Name" type="text" />

Using the typed "TextBoxFor" version allows using compile time checking. So if we change our model then we can check whether there are any errors in your views.

17. How can we do validation in ASP.NET MVC?

Answer:

ASP.NET MVC uses DataAnnotations attributes to implement validations. It is one of the easiest ways to do validation in MVC.

For example, in the code snippet below we have a simple Employee class with a property EmpCode.

This EmpCode property is tagged with a Required data annotation attribute. 

public class Employee
{
    [Required(ErrorMessage="Emp code is required")]
    public string EmpCode
    {
        set;
        get;
    }
}

In order to display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.

<% using (Html.BeginForm("PostEmployee", "Home", FormMethod.Post))
{ %>
    <%=Html.TextBoxFor(m => m.EmpCode)%>
    <%=Html.ValidationMessageFor(m => m.EmpCode)%>
    <input type="submit" value="Submit Employee data" />
<%}%>

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 PostEmployee(Employee obj)
{
    if (ModelState.IsValid)
    {
        obj.Save();
        return View("Thanks");
    }
    else
    {
        return View("Employee");
    }
}

18. What is validation summary?

Answer:

The validation summary is used to display all the error messages in the view. It displays an unordered list of all validation errors in the ModelState dictionary object.

Example:

@Html.ValidationSummary(true) @*//shows model-level errors*@
@Html.ValidationSummary(false) @*//shows model-level and property-level errors*@



19. What is View Engine?

Answer:

View Engine is responsible for rendering view into html form to the browser. By default, Asp.net MVC supports Web Form(ASPX) and Razor View Engine. There are many third party view engines (like Spark, Nhaml etc.) that are also available for Asp.net MVC.  

For example, ASP.NET comes with its own view engine out of the box. That is the one where views have lots of tags like <% %> and <%: %>. It uses the .aspx file extension.

With ASP.NET MVC3, another out-of-the-box view engine was added, Razor, which has a more appealing syntax, e.g. <div>@Model.UserName</div>.

20. What is Razor in MVC?

Answer:

The Razor View Engine is an advanced view engine, available with MVC 3.0 and later versions. Razor uses "@" character instead of "<% %>" as used by the ASPX View Engine.

Razor is an advanced view engine and it is compact, expressive and also reduces typing.
e.g.
@Html.ActionLink("SignUp", "SignUp")

21. What is the difference between Razor and web form engine?

Answer:

Razor View EngineWeb form view engine
Razor syntax is very compact that reduces typing.It has the syntax which is same as an ASP.Net form application.
The namespace for Razor Engine is System.Web.Razor.The namespace for Webform Engine is System.Web.Mvc.WebFormViewEngine.
Razor view engine uses @ symbol to render server-side content.It uses "<%= %>" or "<%: %>" to render server-side content.
The Razor engine supports test driven development (TDD).Webform view engine does not support test driven development.
Razor has no file dependency.ASPX files have a dependency on the ASP.NET runtime  to parse and execute those ASPX files.
The Razor View Engine prevents Cross Site Scripting (XSS) attacks by encoding the script or HTML tags before rendering to the view.A web form View engine does not prevent Cross Site Scripting (XSS) attack.
Razor engine doesn't support design mode in visual studio.Web form engine supports design mode in visual studio, means we can see look and feel of our page without running the application.

22. How can we perform authentication and authorization in ASP.NET MVC?

Answer:

We can use both Windows and Form authentication in ASP.NET MVC.

Implement Windows authentication for MVC:
For windows authentication we need to modify the web.config file and set the authentication mode to Windows.

<system.web>
    <authentication mode="Windows"/>
    <authorization>
            <deny users="?"/>
    </authorization>
</system.web>

Implement Form authentication for MVC:
The first step is to set the authentication mode to "Forms". The loginUrl points to a controller rather than a page.

<system.web>
    <authentication mode="Forms">
        <forms loginUrl="∼/Home/Login"  timeout="20"/>
    </authentication>
</system.web>

23. What is Areas in MVC?

Answer:

ASP.NET MVC 2 introduced Area. Area allows partitioning of large application into smaller units where each unit contains separate MVC folder structure, same as default MVC folder structure.

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.

24. What is ViewStart? and when to use ViewStart?

Answer:

The _ViewStart.cshtml page is a special view page containing the statement declaration to include the Layout page. Instead of declaring the Layout page in every view page, we can use the _ViewStart page. When a View Page Start is running, the “_ViewStart.cshtml” page will assign the Layout page for it.

Example:

//_ViewStart.cshml
@{
    Layout = "∼/Views/Shared/Layout.cshtml";
}

When to Use:
The _ViewStart.cshtml page is used to serve same layout for group of views. The code within this file is executed before the code in any view placed in the same directory. Thus, a view can override the Layout property and choose a different one.


25. What is the difference between ActionResult and ViewResult?

Answer: 

In ASP.NET MVC, ActionResult and ViewResult are mainly a return type for Controller Action method.

ActionResult is an abstract class while ViewResult derives from the ActionResult class.

ViewResult can return only ViewResult type. ActionResult can return many type of Result.

If we are returning different type of view dynamically then ActionResult is best things.

Example 1: ActionResult

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

Example 2: ViewResult

public ViewResult Index()
  {   
      return View();
  }

26. What are the Filters in MVC?

Answer:

Filters: 
ASP.NET MVC filter is a custom class where we can write our custom logic to execute before or after Action method execute. Filter can be applied to an action method or controller.

Filter provides feature to add and post action behaviors on controller's action methods.

Types of Filter:
  • Action Filters: Perform some operation before and after an action method execute and implements the IActionFilter attribute.

  • Authorization Filters: It is used to implement authentication and authorization for controller actions and implements the IAuthorizationFilter attribute.

  • Result Filters: Result filters contain logic that are executed before and after a view result is executed and implement the IResultFilter attribute.

  • Exception Filter: We use exception filter to handle errors raised by either our controller or controller action results and implements the IExceptionFilter attribute.

27. What are the ActionFilters in MVC? What are the different types of action filters?

Answer: 

Action Filters are additional attributes that can be applied to either a controller section or the entire controller to modify the way in which action is executed. These attributes are special .NET classes derived from System.Attribute which can be attached to classes, methods, properties and fields.

ASP.NET MVC provides following action filters:

Output Cache: Output action filter caches the output of a controller action for a specified amount of time.

Handle Error: Handle action filter handles errors raised when a controller action executes.

Authorize: This action filter enables you to restrict access to a particular user or role.

28. What are the ways of handling an Error in MVC?

Answer:

Exception handling is the required part of the each application, whether it is web application or a Window Forms Application.

There are multiple ways to handle exception in ASP.NET MVC. 

1. Using Try catch block
This is the simple ways to handle the exception handling in ASP.NET MVC. When the exception happens the catch block gets executed and it redirect to error view.

2. Override OnException method
The OnException is a void method that takes an argument as an object of ExceptionContext that has all the information about exception. 

We override the "OnException" event of the controller and set the "Result" to the view. This View gets invoked when error occurs in the controller.

3. Using HandleError attribute
ASP.Net MVC has an attribute called "HandleError" that provides built-in exception filters.

We can define "HandleError" attributes as shown below.

public class HomeController : Controller
{
        [HandleError()]
        public ActionResult Index()
        {
            throw new Exception("Demo");
        }
}

4. Global Error Handling in MVC
If you want global error handling across the application, then override the "Application_Error" event and redirect the page from the global error.

29. What is Bundling and Minification in MVC?

Answer:

Bundling and Minification concept are introduced in MVC 4 and .NET framework 4.5. Both techniques are used to reduce the number of requests to the server and size of requested CSS and JavaScript, which improve page loading time.

Bundling:
Bundling helps us combine multiple JavaScript and CSS files into a single entity thus minimizing multiple requests into a single request.

Minification:
Minification is technique for removing unnecessary characters (like white space, newline, tab) and comments from the JavaScript and CSS files to reduce the size which cause improved load times of a webpage.

For example consider following JavaScript code.

Example:

sayHello = function(wish){
    //this is comment
    var msg = "Hello" + wish;
    alert(msg);
}

The above JavaScript will be optimized and minimized into following script.

sayHello=function(n){var t="Hello"+n;alert(t)}

30. What is GET and POST Actions Types?

Answer:

GET - GET is used to request data from a specified resource. With the entire GET request we pass the URL which is compulsory, however it can take the following overloads.

.get(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ).done/.fail

POST - POST is used to submit data to be processed to a specified resource. With all the POST requests we pass the URL (compulsory) and the data, however it can take following overloads.

.post(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )



31. What is Scaffolding?

Answer:

Scaffolding is the technique for code generation for ASP.NET web application. This technique is used by many MVC frameworks like ASP.NET MVC, Node JS etc for code generation. Using Scaffolding we can reduce the amount of time to develop standard data operation in our project. 

Scaffolding consists of page templates, entity page templates, field page templates, and filter templates. These are called Scaffolding templates.

32. What is JsonResult in ASP.NET MVC?

Answer:

"JSON" (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. It provides an efficient mechanism to exchange data between the web browser and the web server.

The JSON format is an open standard format. The format of data looks very easy to understand and the data object consists of attribute-value pairs.

JsonResult Class is inherited from the "ActionResult" abstract class. Action methods in controllers return JsonResult that can be used in AJAX application. The JsonResult represents a class that is used to send JSON-formatted content to the response.

Example:
public ActionResult Movies()
{
    Return Json("Avengers!");
}

33. What is caching and when to use it?

Answer:

Caching is used to enhance the performance of the ASP.NET MVC web application. Caching provides a way of storing frequently accessed data and reusing that data.

In ASP.NET MVC, OutputCache attribute is used for applying Caching. OutputCaching will store the output of a Controller in memory and if any other request comes for the same, it returns the output from cache result.

When to use:
  • Avoid caching content which is unique for every user or rarely used.
  • Cache frequently used content.
  • Define a short cache expiration time rather than disabling caching.

34. What is loose coupling and how is it possible?

Answer: 

Loose coupling is a software design where all classes can work independently without relying on each other.

MVC design pattern enables us to develop application's components independently which allows testing and maintenance of our application easier. 

Using Dependency Injection, you can develop loosely coupled application's components.

35. How can we do exception handling in MVC?

Answer:

In controller section we can override the "OnException" event and set the "Result" to the view name which we want to invoke when error occurs. In the code below you can see we have set the "Result" to a view named as "Error".

public class HomeController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        Exception ex = filterContext.Exception;
        filterContext.ExceptionHandled = true;
        var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");
        filterContext.Result = new ViewResult()
        {
            ViewName = "Error",
            ViewData = new ViewDataDictionary(model)
        };
    }
}

To display above error in view, we use this code.

@Model.Exception;

36. What is Layout View?

Answer:

ASP.NET MVC layout is like Master page in ASP web form. Using Layout view we maintain a consistent look and feel across all the pages within our web application. Layout may contain common jQuery, CSS file across multiple Views. 

The Layout view provides the code reusability that eliminates the duplicate code and enhances development speed and allows easy maintenance.
Following are the auto generated _Layout.cshtml.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("∼ /Content/css")
    @Scripts.Render("∼ /bundles/modernizr")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>© @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    @Scripts.Render("∼ /bundles/jquery")
    @Scripts.Render("∼ /bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

The _ViewStart File

The _ViewStart.cshtml in the Views folder contains the following content.
@{
    Layout = "∼ /Views/Shared/_Layout.cshtml";
}



37. What are Sections in ASP.NET MVC?

Answer:

A section allows us to define a region of content within a layout. It accepts one parameter which is the name of the section.

A section in a layout page that can be defined by using the following code.

@section header{
    <h1>Header Content</h1>
}


We  can render above defined section header on the content page as given below:

@RenderSection("header")

38. What are AJAX helpers?

Answer:

Ajax helper of ASP.NET MVC provides the Ajax functionality to our web application. Ajax helpers are used to create Ajax enable elements like as Ajax enable form and links which perform request asynchronously. AJAX Helpers are extension methods of AJAXHelper class which exist in System.Web.Mvc namespace.

In the example below we create AJAX-enabled link based on action/controller.

@Ajax.ActionLink("Load Products", "GetProducts", new AjaxOptions {UpdateTargetId = "Products-container", HttpMethod = "GET" })

Output: 

<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#Products-container" href="/Home/GetProducts">Load Products</a>

39. What is Cross Domain Ajax?

Answer:

By default web browser allows Ajax call only from the origin of the application where our site is hosted. This restriction helps us to prevent cross site scripting (XSS) attacks.

When we want to interact with externally hosted APIs then our web application must support JSONP request or Cross-Origin Resource Sharing.

40. What is the NonAction attributes in ASP.NET MVC?

Answer:

In MVC framework, all the public methods of the controller class are treated as Action method. If our controller class contains a public method and we do not want it to be an action method, then we must mark that method with the NonActionAttribute attribute.

Example:

[NonAction]
public void TestMethod()
{
   // Method logic
}







No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...