ASP .Net MVC Interview Questions

MVC is a framework methodology that divides an application’s implementation into three component roles: models, views, and controllers.

MVC 3
ASP.NET MVC 3 is a framework for building scalable, standards-based web applications using well-established design patterns and the power of ASP.NET and the .NET Framework.

What does Model, View and Controller represent in an MVC application?

Model: represents the application data domain. In short the applications business logic is contained with in the model. 
View: represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.
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. The user input logic is contained with in the controller.

What is the ‘page lifecycle’ of an ASP.NET MVC?
Any web application has two main execution steps, first understanding the request and depending on the type of the request sending out appropriate response. 

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.

Following process are performed by ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view

ViewModel :  is a “Model of the View” meaning it is an abstraction of the View that also serves in data binding between the View and the Model.
      ViewModel  acts as a data binder/converter that changes Model information into View information and passes commands from the View into the Model. The ViewModel exposes public properties, commands, and abstractions.
to know more about 
Click here

What's the base class of a Razor View in ASP.NET MVC?
System.Web.Mvc.WebViewPage

Test Driven Development is the process where the developer creates the test case first and then fixes the actual implementation of the method. It happens this way, first create a test case, fail it, do the implementation, ensure the test case success, re-factor the code and then continue with the cycle again.

What is the greatest advantage of using asp.net mvc over asp.net webforms?
The main advantages of ASP.net MVC are: Enables the full control over the rendered HTML.
 Provides clean separation of concerns(SoC).
Enables Test Driven Development (TDD).

it is difficult to unit test UI with webforms, where Views in mvc can be easily unit tested.
Easy integration with JavaScript frameworks.Following the design of stateless nature of the web.
RESTful urls that enables SEO.
No ViewState and PostBack events
SEO friendly
Complex applications can be easily managed

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 main advantage of ASP.net Web Form are:
It provides RAD development
Easy development model for developers those coming from winform development.


Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?
Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.

ASP.NET MVC 4 Features: 
  1. ASP.NET Web API
  2. Refreshed and modernized default project templates
  3. New mobile project template
  4. Many new features to support mobile apps
  5. Display Modes
  6. Bundling and Minification
  7. Enabling Logins from Facebook and Other Sites Using OAuth and OpenID
Bundling[MVC4]: 
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 means fewer HTTP requests and that can improve first page load  performance.

Minification[MVC4]:
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.

Display Modes[MVC4]:
The new Display Modes feature lets an application select views depending on the browser that's making the request. For example, if a desktop browser requests the Home page, the application might use the Views\Home\Index.cshtml template. If a mobile browser requests the Home page, the application might return the Views\Home\Index.mobile.cshtml template.

Controlling Bundling and Minification
Bundling and minification is enabled or disabled by setting the value of the debug attribute in the compilation Element  in the Web.config file. In the following XML, debug is set to true so bundling and minification is disabled.
<system.web>
    <compilation debug="true" />
    <!-- Lines removed for clarity. -->
</system.web>
To enable bundling and minification, set the debug value to "false". You can override the Web.config setting with theEnableOptimizations property on the BundleTable class. The following code enables bundling and minification and overrides any setting in the Web.config file.
public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                 "~/Scripts/jquery-{version}.js"));

    // Code removed for clarity.
    BundleTable.EnableOptimizations = true;
}
for more info about this Topic follow the Link MVC-4/Bundling-and-Minification

 ASP.NET Core MVC and ASP.NET MVC 5:   Click here

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.

Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax

Name a few different return types of a controller action method?

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

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

What is the difference between ViewResult() and ActionResult() in ASP.NET MVC?
ActionResult is an abstract class.
ViewResult derives from ActionResult. Other derived classes include JsonResult and PartialViewResult.
The View() method returns a ViewResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult one, your controller isn't promising to return a view - you could change the method body to conditionally return a RedirectResult or something else without changing the method definition.

see that Code :

public ActionResult Foo()
        {
            if (1==2)
                return View(); // returns ViewResult
            else
                return Json(new { foo = "bar", baz = "Blech" }, JsonRequestBehavior.AllowGet); // returns JsonResult
        }

DIFFERENCE BETWEEN @Html.TextBox and @Html.TextBoxFor

Html.TextBox is not strongly typed and it doesn't require a strongly typed view meaning that you can hardcode whatever name you want as first argument and provide it a value:
@Html.TextBox("foo", "some value")

You can set some value in the ViewData dictionary inside the controller action and the helper will use this value when rendering the textbox (ViewData["foo"] = "bar").

Html.TextBoxFor is requires a strongly typed view and uses the view model:
@Html.TextBoxFor(x => x.Foo)

The helper will use the lambda expression to infer the name and the value of the view model passed to the view.

And because it is a good practice to use strongly typed views and view models you should always use the Html.TextBoxFor helper.

What is AntiForgeryToken() in MVC?
Generates a hidden form field (anti-forgery token) that is validated when the form is submitted.
        The anti-forgery token can be used to help protect your application against cross-site request forgery. To use this feature, call the AntiForgeryToken method from a form and add the ValidateAntiForgeryTokenAttribute attribute to the action method that you want to protect.
to know more Click here

What is the significance of ASP.NET routing?
Routing is a URL Pattern that Maps incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.

There are two types of routing (after the introduction of ASP.NET MVC 5).

Convention based routing: to define this type of routing, we call MapRoute method and set its unique name, url pattern and specify some default values.

Attribute based routing: to define this type of routing, we specify the Route attribute in the action method of the controller.


Route constraints MVC5
We can also specify parameter constraints placing the constraint name after the parameter name separated by colon. For example we can specify that the parameter type should be integer by using the following
[Route("User/Profile/{id:int}")]

Now if we do not specify integer parameter then the route will not match even if other segments match.
Route Prefix - MVC5
If we have multiple action methods in a controller all using the same prefix we can use RoutePrefix attribute on the controller instead of putting that prefix on every action method.
Like we can attach the following attribute on the controller
[RoutePrefix("User")]

So now our Route attribute on our action method does not need to specify the common prefix
[Route("Profile/{id}")]

How route table is created in ASP.NET MVC?
When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.


Attribute based routing in MVC5
Using attribute based routing we can define the route in the same place where action method is defined. Following is an example of a route defined using the Route attribute. 

        [Route("User/Profile/{id}")]
        public ActionResult GetUserProfile(string id)
        {
            ViewBag.Id = id;
            return View();
        }

To enable attribute based routing we need to add the following in the RouteConfig file.

 public static void RegisterRoutes(RouteCollection routes)
 {
    routes.MapMvcAttributeRoutes();
 }

Optional Parameter in URL- MVC5
We can also specify if there is any optional parameter in the URL pattern defined by the Route attribute with the “?” character. If the above action method is called and the value for “id” parameter is not provided we will get an exception since id is a required parameter. We can make it an optional parameter by making the following changes.

  [Route("User/Profile/{id?}")]
  public ActionResult GetUserProfile(int? id)
  {
    ViewBag.Id = id; return View();

  }

ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are these 2 places?
1. Web.Config File : ASP.NET routing has to be enabled here.
2. Global.asax File : The Route table is created in the application Start event handler, of the     Global.asax file.

Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax

What is the use of action filters in an MVC application?
Action Filters allow us to add pre-action and post-action behavior to controller action methods.

If I have multiple filters impleted, what is the order in which these filters get executed?
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters

Action Filters
There are a set of Action filters available with ASP.NET MVC 3 to filter actions. Action filters are defined as attributes and applied to an Action or controller.

1. Authorize
Authorize filters ensure that the corresponding Action will be called by an authorized user only. If the user is not authorized, he will be redirected to the login page.

[Authorize]
public ActionResult About()
{
    return View();
}

2. HandleError

HandleError will handle the various exceptions thrown by the application and display user friendly message to the user. By default, this filter is registered in Global.asax.
Give an example for Authorization filters in an asp.net mvc application?
1. RequireHttps Attribute
2. Authorize Attribute

Action Selectors
ASP.NET MVC 3 defines a set of Action selectors which determine the selection of an Action. One of them is ActionName, used for defining an alias for an Action. When we define an alias for an Action, the Action will be invoked using only the alias; not with the Action name.

[ActionName("NewAbout")]

public ActionResult About()
{
    return Content("Hello from New About");
}

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

What is Razor View Engine?
Razor view engine is a new view engine created with ASP.Net MVC. It allows us to write Compact, Expressive, Clean and Fluid code with new syntaxes to include server side code in to HTML. Razor uses @ symbol to make the code.

What is difference between Viewbag and Viewdata in ASP.NET MVC?
The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.

ViewData requires typecasting for complex data type and check for null values to avoid error.ViewBag doesn’t require typecasting for complex data type.
ViewData and ViewBag are used to pass data from controller to corresponding view.

Difference between tempdata , viewdata and viewbag
Temp data: -Helps to maintain data when you move from one controller to other 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.
View data: - Helps to maintain data when you move from controller to view.
View Bag: - It’s a dynamic wrapper around view data. When you use “Viewbag” type casting is not required. It uses the dynamic keyword internally.

Below is a summary table which shows different mechanism of persistence.
Maintains data between ViewData/ViewBag ,TempData, Hidden fields,Session

                                    ViewData/ViewBag TempData Hidden fields Session
Controller to Controller            No                         Yes                  No                  Yes
Controller to View                   Yes                        No                    No                  Yes
View to Controller                   No                          No                  Yes                   Yes

Partial View: A partial view is like as user control in Asp.Net Web forms that is used for code re-usability. Partial views helps us to reduce code duplication. Hence partial views are reusable views like as Header and Footer views. We can use partial view to display blog comments, product category, social bookmarks buttons, a dynamic ticker, calendar etc. 


Whats the difference between Html.Partial and Html.RenderPartial ?
The Partial helper renders a partial view into a string.
RenderPartial writes directly to the response output stream instead of returning a string

Value Provider and Model Binder
ASP.NET 4.5 Web Forms support model binding. A part of the overall model binding features are Value Providers. A value provider grabs values from a request and binds those values with method parameters. 

The framework contains a few built-in value providers named FormValueProvider, RouteDataValueProvider, QueryStringValueProvider and HttpFileCollectionValueProvider that fetch data from Request.Form, Request.QueryString, Request.Files and RouteData.Values.

NonActionAttribute 

By default, the MVC framework treats all public methods of a controller class as action methods. If your controller class contains a public method and you do not want it to be an action method, you must mark that method with the NonActionAttribute attribute.
https://stackoverflow.com/

What is Repository Pattern?
In simple terms, a repository basically works as a mediator between our business logic layer and our data access layer of the application. In a Repository we write our entire business logic of CRUD operations using Entity Framework classes.. The web application doesn't know anything about the data access , the repository is in charge of that.
The nice thing about the repository pattern is that it makes it easier to unit test your app and easier to maintain your application.
it makes it easy to change data access layer. If you want to switch from a local DB to a cloud based db, it's easy with the repository pattern.
to Read More Click on the below Link:


Why The Repository Pattern and Unit of Work in MVC and EntityFramework?


Anonymous Methods: – In simple words Anonymous Methods means method which are coded inline or methods without method name.
An anonymous method uses the keyword delegate, instead of method name.
JSON(JavaScript Object Notation) - JSON is a lightweight, language independent data interchange format. Much like XML.

JSON is lightweight text-data interchange format.
JSON is language independent .
JSON is "self-describing" and easy to understand.
JSON is smaller than XML, and faster and easier to parse.

*****************************************************************************

What is Entity Framework?
Entity Framework is an additional layer between application and database that enables the developers to program against the conceptual application model instead of programming directly against the relational storage schema.  The goal is to decrease the amount of code and maintenance required for data-oriented applications.

What is CSDL?
Conceptual schema definition language (CSDL) is an XML-based language that describes the entities, relationships, and functions that make up a conceptual model of a data-driven application. This conceptual model can be used by the Entity Framework or WCF Data Services.

What is SSDL?
Store schema definition language (SSDL) is an XML-based language that describes the storage model of an Entity Framework application.

What is .edmx file and what it contains?

An .edmx file is an XML file that defines a conceptual model, a storage model, and the mapping between these models. An .edmx file also contains information that is used by the ADO.NET Entity Data Model Designer (Entity Designer) to render a model graphically.

What is Code First Approach?
in this Approach we dont need to create a Database and Table First. we dont need to add edmx File in project. Code First allows you to define your model using C# classes and Your model can be used to generate a database schema or to map to an existing database.


What is LINQ To Entities?
LINQ to Entities provides Language-Integrated Query (LINQ) support for querying entities.

What is Deferred Loading(Lazy Loading)?
When objects are returned by a query, related objects are not loaded at the same time.

What is Mapping in Entity Framework?
Mapping consist information about how your conceptual model is mapped to storage model

What is Conceptual Model?
Conceptual model is your model classes and their relationships. This will be independent from your database table design.
What is Storage Model?Storage model is your database design model which includes tables, views, stored procedures and their relationships and keys.


What are Complex Types?
Complex types are a way to encapsulate a set of entity’s properties inside a structure which isn’t an entity. You use them to organize properties into structures that make your design more understandable. For example, you can have a Customer entity which has properties that make an address.
You can arrange these properties in a Address complex type. Complex types are a conceptual entities types.


What are context class?
The context class is responsible for managing  the entity objects during run time, which includes populating objects with data from a database, change tracking, and persisting data to the database.

public class ProductContext : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
}

Difference between DBContext vs ObjectContexts
ObjectContext is only useful in Model First and Database First approach. You should use DBContext if you use Entity Framework 4.1 and above.

DBSet class represents an entity set that is use for create, read, update, and delete operations.

POCOS(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. POCO allows you to write your own entity classes. POCOS are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like

·         Lazy loading
·         Change tracking

Read More about POCO Click here

Change tracking is a central concept for every Object-Relational Mapper, including Entity Framework. In an Entity Framework application, an object context is responsible for tracking changes in the entities. When doing updates to objects the normal work flow with Entity Framework has three steps.

1.       Retrieve data from the database.
2.       Update some properties on some objects.
3.       Save the updates to the database

to read more about Entity Framework Click @ me!
*****************************************************************************

LINQ is a technique for querying data from any Datasource. data source could be the collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.

Advantages:  as Linq Queries is integrated with .net c# language , it enables you to write code much faster then than if you were writing oldstyle queries. In some cases I have seen, by using LINQ development time cut in half.

Ex:
int[] nums = new int[] {0,1,2};
var res = from a
in nums
             where a < 3
             orderby a
             select a;
foreach(int i in res)
    Console.
WriteLine(i);

*****************************************************************************

Dependency Injection basically allows us to create loosely coupled, reusable, and testable objects in your software designs by removing dependencies.


 IoC (inversion of control) is a design pattern used to uncouple classes to avoid strong dependencies between them.


 What are the different types of IOC (dependency injection) ? 

There are four types of dependency injection:

  • Constructor Injection): Dependencies are provided as constructor parameters.
  • Getter-Setter Injection : Dependencies are assigned through properties (ex: setter methods).
  • Interface Injection Injection is done through an interface.
  • Service Locater:

 What is the difference between loose coupling and tight coupling in object oriented paradigm?

 Tight coupling means the two classes often change together, loose coupling means they are mostly  independent.

          In general, loose coupling is recommended because it's easier to test and maintain.

 Tight coupling is when a group of classes are highly dependent on one another.

A loosely-coupled class can be consumed and tested independently of other (concrete) classes.

*******************************************************************************
The view engine is responsible for creating HTML from your views. Views are usually some kind of mixup of HTML and a programming language. 
The Razor View EngineIt’s a type of View Engion that is introduced in MVC3 that offers some benefits that like:
1- Razor syntax is clean and concise, requiring a minimum number of code.
2- it's based on existing languages like C# and Visual Basic.
3- Razor views can be unit tested without requiring that you run the  application or launch a web server.

Some new Razor features include the following:

·         @model syntax for specifying the type being passed to the view.

·         @* *@ comment syntax.

·         The ability to specify defaults (such as layoutpage) once for an entire site.

·         The Html.Raw method for displaying text without HTML-encoding it.

·         Support for sharing code among multiple views (_viewstart.cshtml or _viewstart.vbhtml files).


Razor also includes new HTML helpers, such as the following:

·         Chart. Renders a chart, offering the same features as the chart control in ASP.NET 4.

·         WebGrid. Renders a data grid, complete with paging and sorting functionality.

·         Crypto. Uses hashing algorithms to create properly salted and hashed passwords.

·         WebImage. Renders an image.

·         WebMail. Sends an email message.


for more interview Questions follow the link - 
http://www.codeproject.com/Articles/556995/Model-view-controller-MVC-Interview-questions-and
https://www.c-sharpcorner.com/UploadFile/8ef97c/most-asked-Asp-Net-mvc-interview-questions-and-answers/

JsonConvert.SerializeObject()
Serializes the specified object to a JSON string in c#.

Example: 

Employee employee=new Employee
{
 FirstName = "Suraj",
 LastName = "Kumar"
};
string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(employee);
Console.WriteLine(jsonString);

For More information : Click here

JavaScriptSerializer Class

Json.NET should be used serialization and deserialization. Provides serialization and deserialization functionality for AJAX-enabled applications.

Example:  The below example provides a simple illustration of how to serialize and deserialize data objects. It requires a class names Employee which is shown below.

Employee employee=new Employee
{
 FirstName = "Suraj",
 LastName = "Kumar"
};
var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(employee);
var deserializedResult = javaScriptSerializer.Deserialize<Employee>(employeeDetail);

For More information : Click here

Why is JsonRequestBehavior needed in Jsonresult method?

By default, the ASP.NET MVC framework does not allow you to respond to an HTTP GET request with a JSON payload. If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet as the second parameter to the Json method.

What is the difference between $.ajax() and $.get()

$.ajax()
Perform an asynchronous HTTP (Ajax) request.
$.ajax() is the most configurable one, where you get fine grained control over HTTP headers and such. You have to deal with the returned data yourself with a callback.

$.get()
Load data from the server using a HTTP GET request.

$.get() is just a shorthand for $.ajax(). Returns the data to a callback.

4 comments:

  1. Very knowledgeable post. I recommend this page for new person planning to learn MvC.

    ReplyDelete
  2. Nice work, your blog is concept-oriented, kindly share more blogs like this
    Dot NET Online Training Hyderabad

    ReplyDelete
  3. very informative blog and useful article thank you for sharing with us , keep posting learn more Ruby on Rails Online Course Hyderabad

    ReplyDelete

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)