Expert Dot Net

Trust me to find new way !

ASP.NET MVC Interview Questions

Q1 - What is MVC (Model view controller)?

 Answer

Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representation of information from the way that information is presented to or accepted from the user.

MVC is a framework for building web applications using a MVC (Model View Controller) design:

The Model represents the application core (for instance a list of database records).

The View displays the data (the database records).

The Controller handles the input (to the database records).

The MVC model also provides full control over HTML, CSS, and JavaScript.




The MVC model defines web applications with 3 logic layers,

The business layer (Model logic)

The display layer (View logic)

The input control (Controller logic)


The Model is the part of the application that handles the logic for the application data.

Often model objects retrieve data (and store data) from a database.



The View is the part of the application that handles the display of the data.

Most often the views are created from the model data.



The Controller is the part of the application that handles user interaction.

Typically controllers read data from a view, control user input, and send input data to the model.

The MVC separation helps you manage complex applications, because you can focus on one aspect a time. For example, you can focus on the view without depending on the business logic. It also makes it easier to test an application.

The MVC separation also simplifies group development. Different developers can work on the view, the controller logic, and the business logic in parallel.

 

Q2. Explain in which assembly is the MVC framework is defined?


Answer

The MVC framework is defined in System.Web.Mvc.


Q4. List out few different return types of a controller action method?

Answer

View Result

Javascript Result

Redirect Result

Json Result

Content Result


Q5.  Mention what is the advantages of MVC?


Answer

MVC segregates your project into a different segment, and it becomes easy for developers to work on

It is easy to edit or change some part of your project that makes project less development and maintenance cost

MVC makes your project more systematic

 

Q6. Explain the role of components Presentation, Abstraction and Control in MVC?


Answer

Presentation: It is the visual representation of a specific abstraction within the application

Abstraction: It is the business domain functionality within the application

Control: It is a component that keeps consistency between the abstraction within the system and their presentation to the user in addition to communicating with other controls within the system


Q7- Explain MVC application life cycle?


Answer

 Any web application has two main execution steps, first understanding the request and depending on the type of the request sending 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.


Creating the request object,

The request object creation has four major steps. The following is the detailed explanation of the same.

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 - Fetch route

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.




Q8 - List out different return types of a controller action method?

 

Answer

 

There are total nine return types we can use to return results from controller to view.


The base type of all these result types is ActionResult.

ViewResult (View)
This return type is used to return a webpage from an action method.

PartialviewResult (Partialview)
This return type is used to send a part of a view which will be rendered in another view.

RedirectResult (Redirect)
This return type is used to redirect to any other controller and action method depending on the URL.

RedirectToRouteResult (RedirectToAction, RedirectToRoute)
This return type is used when we want to redirect to any other action method.

ContentResult (Content)
This return type is used to return HTTP content type like text/plain as the result of the action.

jsonResult (json)
This return type is used when we want to return a JSON message.

javascriptResult (javascript)
This return type is used to return JavaScript code that will run in browser.

FileResult (File)
This return type is used to send binary output in response.

EmptyResult
This return type is used to return nothing (void) in the result.

 

 

Q9. What is Razor in MVC?

Answer

 

ASP.NET MVC has always supported the concept of “view engines” – which are the pluggable modules, which practically implement different template syntax options. The “default” view engine for ASP.NET MVC uses the same .aspx/.ascx/. master file templates as ASP.NET Web Forms. Other popular ASP.NET MVC view engines are Spart&Nhaml. Razor is the new view engine introduced by MVC 3.

 

Q10. Explain what is Database First Approach in MVC using Entity Framework?

Answer

 

Database First Approach is an alternative or substitutes to the Code First and Model First approaches to the Entity Data Model. The Entity Data Model creates model codes (classes, properties, DbContext, etc.) from the database in the project and that class behaves as the link between database and controller.

There are the following approaches, which are used to connect the database with the application.

Database First

Model First

Code First

Learn ASP.NET MVC Filters and Attributes

In ASP.NET MVC, controllers define action methods and these action methods generally have a one-to-one relationship with UI controls, such as clicking a button or a link, etc. For example, in one of our previous examples, the UserController class contained methods UserAdd, UserDelete, etc.


However, many times we would like to perform some action before or after a particular operation. For achieving this functionality, ASP.NET MVC provides a feature to add pre- and post-action behaviors on the controller's action methods.


Types of Filters

ASP.NET MVC framework supports the following action filters −


  1. Action Filters − Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter.
  2. Authorization Filters − Authorization filters are used to implement authentication and authorization for controller actions.
  3. Result Filters − Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
  4. Exception Filters − Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.


Action filters are one of the most commonly used filters to perform additional data processing, or manipulating the return values or cancelling the execution of action or modifying the view structure at run time.


Action Filters

Action Filters are additional attributes that can be applied to either a controller section or the entire controller to modify the way in which an 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 the following action filters −


  1. Output Cache − This action filter caches the output of a controller action for a specified amount of time.
  2. Handle Error − This action filter handles errors raised when a controller action executes.
  3. Authorize − This action filter enables you to restrict access to a particular user or role.


Now, we will see the code example to apply these filters on an example controller ActionFilterDemoController. (ActionFilterDemoController is just used as an example. You can use these filters on any of your controllers.)


Output Cache

Example − Specifies the return value to be cached for 10 seconds.

Visual Studio 2017 New Feature

Visual Studio 2017 New Feature

1 - Visual Studio 2017 Installer

Visual Studio 2017 comes with a brand new, revamped installer. I have never been a fan of the previous Visual Studio installers. It literally took forever to install Visual Studio. It was, in my opinion, a very painful experience and I dreaded every time I had to install a new version of Visual Studio. Now, the process is far less painful.

The new installer for Visual Studio 2017 has the following features:

  • Installs more quickly with less system impact.
  • Uninstalls cleanly.
  • Reduces the footprint of Visual Studio.
  • Makes it easier for you to select and install just the features you need.


2 - A New Visual Studio Start Page

The new Visual Studio 2017 Start Page has new Open and Create facilities, including:

  • Updated badge on newly added items in the News Feed.
  • Dismissible "Get Started" section.
  • The Visual Studio 2017 Start Page Most Recent Used items (MRU) shows repos that you have cloned on other machines so that you can easily clone them on your current machine.
  • Create new projects directly from the Start Page with searchable templates and a list of recently used templates.
  • Refined visual design to address feedback about truncated elements on smaller screens and utilization of empty space.

3 - New Extensibility Features
The new Visual Studio 2017 installer gives you greater control over the tools that are installed. Users will be warned when attempting to install an extension that was not built using the new VSIX format.

4 - Live Unit Testing
Live Unit Testing visualizes unit test results and code coverage live on the editor, as you are coding. It works with C# and VB projects and supports three test frameworks: MS Test, xUnit, and NUnit. Currently, Live Unit Testing is only present in the Enterprise edition of Visual Studio 2017.

5 - Run to Click Debugging
You can simply click the icon next to a line of code whilst debugging to run to that line. You no longer have to set temporary breakpoints or perform several steps to execute your code and stop on the line you want.

6 - The New Visual Studio 2017 Exception Helper
  • You can use the new Exception Helper in Visual Studio 2017 to view exception information in a compact, non-modal dialog with instant access to inner exceptions.
  • Quickly see what was null inside the Exception Helper when diagnosing a NullReferenceException.
  • You can exclude breaking on exception types thrown from specific modules.

7 -  Language Extensions

C#
  • Task-like return types for async methods.
  • Value tuples that introduce language support for using tuples to temporarily group a set of typed values.
  • Nested local functions that support declaration of functions in a block scope.
  • Pattern matching extensions.
  • Ref returns that enable functions to return values by reference.
Visual Basic
  • Value tuples; for example: Dim point As (x As Integer, y As Integer) = GetOffset().
  • ByRef return consumption supports consumption of functions and properties from libraries that have ByRef returns.
  • Binary literals and digit group separators allow native representation of binary numbers.

C# For Loop

Loop is used in programming when you need to repeat any group of statement or statement more then one time. For loop is one important looping construct which is used to iterate set of instructions.


for ( int i=0 ; i <= 5 ; i++)

{

// Your statements

}


There are 4 parts of this for loop.


- First part is initialization

- Second part is condition checking

- Third part is increment / decrements

- Fourth part is group of statements which basically would be executed.


Demo 1 :




New Features introduces in .NET 4.5 and 5.0

C# evolution look in a glance : 


1. Parallel.ForEach

Parallel.ForEach is a feature introduced by the Task Parallel Library (TPL). This feature helps you run your loop in parallel. You need to have a multi-processor to use of this feature.

Simple foreach loop

foreach (string i in listStrings)
{
// put your statement here
}

Parallel foreach

Parallel.Foreach(listStrings, text=>
{
// put your statement here
});

2. BigInteger

BigInteger is added as a new feature in the System.Numerics DLL. It is an immutable type that represents a very large integer whose value has no upper or lower bounds.

BigInteger obj = new BigInteger("123456789123456789123456789");


3. ExpandoObject

The ExpandoObject is part of the Dynamic Language Runtime (DLR). One can add and remove members from this object at run time.

Create a dynamic instance.

dynamic Person = new ExpandoObject();
Person.ID = 1001;
Person.Name = "Princy";
Person.LastName = “Gupta”; 

4. Named and Optional Parameters

Optional Parameters

A developer can now have some optional parameters by providing default values for them. PFB how to create optional parameters.

Void PrintName(string a, string b, string c = “princy”)
{
     Console.Writeline(a, b, c)
}
We can now call the function PrinctName() by passing either two or three parameters as in the following:

PrintName(“Princy”,”Gupta”,”Jain”);
PrinctName(“Princy”,”Gupta”);

Output

PrincyGuptaJain
PrincyGuptaprincy

Note: An optional parameter can only be at the end of the parameter list.

Named Parameters

With this new feature the developer can pass values to parameters by referring to parameters by names.

Void PrintName(string A, string B
{
}
Function call

PrintName (B: “Gupta”, A: “Princy”);

With this feature we don't need to pass parameters in the same order to a function.

5. Tuple

A Tuple provides us the ability to store various types in a single object.

The following shows how to create a tuple.

Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1,"princy", true);
Var tupleobj = Tuple.Create(1, "Princy", true); 
In order to access the data inside the tuple, use the following:

string name = tupleobj.Item2;
int age = tupleobj.Item1;
bool obj = tupleobj.Item3;

6. Compiler APIs 

 This feature is supposed to come after C# 5.0 – the APIs will expose whatever knowledge the compiler has about the code to the IDE and the developers, through Syntax Tree APIs, Symbol APIs, Binding and Flow analysis APIs and Emit APIs.

You can use following References for more details.

7. Windows Runtime Support

C# and .NET now have deep integration with the Windows Runtime. C# project can compiled into a WinMD file and then referenced from a HTML/JavaScript project. WinRT’s flavor of COM uses the same metadata format used by the Common Language Runtime. This information is stored in WINMD files that show the structure, though not the implementation, of all the public classes. Windows Runtime returns an HRESULT instead of throwing an exception. For well-known HRESULT values, the corresponding exception is thrown, otherwise a COMException is used.

LINQ Aggregate and Sum

using System;

using System.Linq;

using System.Collections;

using System.Collections.Generic;

 

public class LINQDemo4 {

    public static void Main() {

        IEnumerable<int> intSequence = Enumerable.Range(1, 10);

        foreach (int item in intSequence)

            Console.WriteLine(item);

        int sum = intSequence.Aggregate(0, (s, i) => s + i);

        Console.WriteLine(sum);

    }

}

 

LINQ Aggregate Prototype

using System;

using System.Linq;

using System.Collections;

using System.Collections.Generic;

 

public class LINQDemo3 {

    public static void Main() {

        int N = 5;

        IEnumerable<int> intSequence = Enumerable.Range(1, N);

        foreach (int item in intSequence)

            Console.WriteLine(item);

        int agg = intSequence.Aggregate((av, e) => av * e);

        Console.WriteLine("{0}! = {1}", N, agg);

 

    }

}

 

LINQ Aggregate on an array with tenary operator

using System;

using System.Collections;

using System.Collections.Generic;

using System.Text;

using System.Linq;

 

public class LINQDemo2{

   public static void Main(){

       int[] numbers = { 9, 3, 5, 4, 2, 6, 7, 1, 8 };

       var query = numbers.Aggregate(5, (a,b) => ( (a < b) ? (a * b) : a));

    }

}

 

LINQ Aggregate Use

using System;

using System.Collections;

using System.Collections.Generic;

using System.Text;

using System.Linq;

 

public class LINQDemo1 {

    public static void Main() {

        int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        var query = numbers.Aggregate((a, b) => a * b);

    }

}

C# Basic Syntax

C#-Basic Syntax 

C# is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, are said to be in the same class.

For example, let us consider a Rectangle object. It has attributes such as length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating the area, and displaying details.

Let us look at demo of a Rectangle class and discuss C# basic syntax:

using System;
namespace RectangleDemo
{
   class Rectangle 
   {
      // member variables
      double length;
      double width;
      public void Acceptdetails()
      {
         length = 4.5;    
         width = 3.5;
      }
      
      public double GetArea()
      {
         return length * width; 
      }
      
      public void Display()
      {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }
   
   class ExecuteRectangle 
   {
      static void Main(string[] args) 
      {
         Rectangle r = new Rectangle();
         r.Acceptdetails();
         r.Display();
         Console.ReadLine(); 
      }
   }
}

When the above code is compiled and executed, it produces the following result:

Length: 4.5
Width: 3.5
Area: 15.75

The using Keyword

The first statement in any C# program is

using System;

The using keyword is used for including the namespaces in the program. A program can include multiple using statements.

The class Keyword

The class keyword is used for declaring a class.

Comments in C#

Comments are used for explaining code. Compilers ignore the comment entries. The multiline comments in C# programs start with /* and terminates with the characters */ as shown below:

/* This program demonstrates
The basic syntax of C# programming 
Language */

Single-line comments are indicated by the '//' symbol. For example,

}//end class Rectangle    

Member Variables

Variables are attributes or data members of a class, used for storing data. In the preceding program, the Rectangle class has two member variables named length and width.

Member Functions

Functions are set of statements that perform a specific task. The member functions of a class are declared within the class. Our sample class Rectangle contains three member functions: AcceptDetails, GetArea and Display.

Instantiating a Class

In the preceding program, the class ExecuteRectangle contains the Main()method and instantiates the Rectangle class.

Identifiers

An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in C# are as follows:

·        A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.

·        It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.

·        It should not be a C# keyword.