Thursday, 25 September 2014

1000 FAQ -- ASP.NET MVC

What is MVC?
MVC is a framework pattern that splits an application’s implementation logic into
three component roles: models, views, and controllers.
  • Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.
     
  • View: The user interface that renders the Model into a form of interaction.
     
  • Controller: Handles a request from a View and updates the Model that results in a change of the Model's state.
To implement MVC in .NET we need mainly three classes (View, Controller and the Model). 
Explain MVC Architecture?

The architecture is self explanatory. The browser (as usual) sends a request to IIS, IIS searches for the route defined in MVC application and passes the request to the controller as per route, the controller communicates with the model and passes the populated model (entity) to View (front end), Views are populated with model properties, and are rendered on the browser, passing the response to browser through IIS via controllers which invoked the particular View.

What are the new features of MVC2?
ASP.NET MVC 2 was released in March 2010. Its main features are:
  1.       Introduction of UI helpers with automatic scaffolding with customizable templates.
  2.       Attribute-based model validation on both client and server.
  3.        Strongly typed HTML helpers.
  4.        Improved Visual Studio tooling
  5.       There were also lots of API enhancements and “pro” features, based on feedback from developers building a variety of applications on ASP.NET MVC 1, such as:
  •   Support for partitioning large applications into areas.
  •   Asynchronous controllers support.
  •   Support for rendering subsections of a page/site using Html.RenderAction.
  •   Lots of new helper functions, utilities, and API enhancements
What are the new features of MVC3?
ASP.NET MVC 3 shipped just 10 months after MVC 2 in Jan 2011.Some of the top features in MVC 3 included:
  •        The Razor view engine.
  •        Support for .NET 4 Data Annotations.
  •        Improved model validation
  •        Greater control and flexibility with support for dependency resolution and global action filters.
  •        Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding.
  •        Use of NuGet to deliver software and manage dependencies throughout the platform.
What are the new features of MVC4?
Following are the top features of MVC4:
  •       ASP.NET Web API.
  •       Enhancements to default project templates.
  •       Mobile project template using jQuery Mobile.
  •       Display Modes.
  •       Task support for Asynchronous Controllers.
  •       Bundling and minification.

Explain “page lifecycle” of an ASP.NET MVC?
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

Advantages of MVC Framework?
  1.  Provides a clean separation of concerns between UI (Presentation layer), model (Transfer objects/Domain Objects/Entities) and Business Logic (Controller).
  2.  Easy to UNIT Test.
  3.  Improved reusability of views/model. One can have multiple views which can point tosame model and vice versa.
  4.  Improved structuring of the code.

What do you mean by Separation of Concerns?
As per Wikipedia 'the process of breaking a computer program into distinct features that overlap in functionality as little as possible'. MVC design pattern aims to separate content from presentation and data-processing from content. 

Where do we see Separation of Concerns in MVC?
Between the data-processing (Model) and the rest of the application.
When we talk about Views and Controllers, their ownership itself explains separation. The views are just the presentation form of an application, it does not have to know specifically about the requests coming from controller. The Model is independent of View and Controllers, it only holds business entities that can be passed to any View by the controller as required for exposing them to the end user. The controller is independent of Views and Models, its sole purpose is to handle requests and pass it on as per the routes defined and as per the need of rendering views. Thus our business entities (model), business logic (controllers) and presentation logic (views) lie in logical/physical layers independent of each other.

What is Razor View Engine?
Razor is the first major update to render HTML in MVC3. Razor was designed specifically as a view engine syntax. It has one main focus: code-focused templating for HTML generation. Here’s how that same markup would be generated using Razor:

@model MvcMusicStore.Models.Genre
@{ViewBag.Title = "Browse Albums";}
<div class="genre">
<h3><em>@Model.Name</em> Albums</h3>
<ul id="album-list">
@foreach (var album in Model.Albums)
{
<li>
<a href="@Url.Action("Details", new { id = album.AlbumId })">
<img alt="@album.Title" src="@album.AlbumArtUrl" />
<span>@album.Title</span>
</a>
</li>
}
</ul>
</div>

The Razor syntax is easier to type, and easier to read. Razor doesn’t have the XML-like heavy syntax.
of the Web Forms view engine.

What is Unobtrusive JavaScript?
Unobtrusive JavaScript is a general term that conveys a general philosophy, similar to the term
REST (Representational State Transfer). The high-level description is that unobtrusive JavaScript doesn’t intermix JavaScript code in your page markup. For example, rather than hooking in via event attributes like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by their ID or class, often based on the presence of other attributes (such as HTML5 data- attributes).
It’s got semantic meaning, and all of it — the tag structure, element attributes, and so on — should have a precise meaning. Strewing JavaScript gunk across the page to facilitate interaction (I’m looking at you, __doPostBack!) harms the content of the document.

What is JSON Binding?
MVC 3 included JavaScript Object Notation (JSON) binding support via the new
JsonValueProviderFactory, enabling the action methods to accept and model-bind data in JSON format. This is especially useful in advanced Ajax scenarios like client templates and data binding that need to post data back to the server.

What is Dependency Resolution?
MVC 3 introduced a new concept called a dependency resolver, which greatly simplified the use of dependency injection in your applications. This made it easier to decouple application components, making them more configurable and easier to test.
Support was added for the following scenarios:

  •       Controllers (registering and injecting controller factories, injecting controllers)
  •       Views (registering and injecting view engines, injecting dependencies into view pages)
  •       Action fi lters (locating and injecting fi lters)
  •       Model binders (registering and injecting)
  •       Model validation providers (registering and injecting)
  •       Model metadata providers (registering and injecting)
  •       Value providers (registering and injecting)

What are Display Modes in MVC4?
Display modes use a convention-based approach to allow selecting different views based on the browser making the request. The default view engine fi rst looks for views with names ending with .Mobile.cshtml when the browser’s user agent indicates a known mobile device. For example, if we have a generic view titled Index.cshtml and a mobile view titled Index.Mobile.cshtml, MVC 4 will automatically use the mobile view when viewed in a mobile browser.
Additionally, we can register your own custom device modes that will be based on your own custom criteria — all in just one code statement. For example, to register a WinPhone device mode that would serve views ending with .WinPhone.cshtml to Windows Phone devices, you’d use the following code in the Application_Start method of your Global.asax:

DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("WinPhone")
{
ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf
("Windows Phone OS", StringComparison.OrdinalIgnoreCase) >= 0)
});

What is AuthConfig.cs in MVC4?
AuthConfig.cs  is used to configure security settings, including sites for OAuth login.

 What is BundleConfig.cs in MVC4?
 BundleConfig.cs in MVC4 is used to register bundles used by the bundling and minification
 system. Several bundles are added by default, including jQuery, jQueryUI, jQuery  validation, Modernizr, and default CSS references.

 What is FilterConfig.cs in MVC4?
 This is used to register global MVC filters. The only filter registered by default is the    HandleErrorAttribute, but this is a great place to put other filter registrations.

 What is  RouteConfig.cs in MVC4?
 RouteConfig.cs holds the granddaddy of the MVC config statements, Route configuration.

 What is WebApiConfig.cs in MVC4?
 Used to register Web API routes, as well as set any additional Web API configuration settings.

What’s new in adding controller in MVC4 application?
Previously(in MVC3 and MVC2), the Visual Studio Add Controller menu item only displayed when we right-clicked on the Controllers folder. However, the use of the Controllers folder was purely for organization. (MVC will recognize any class that implements the IController interface as a Controller, regardless of its location in your application.) The MVC 4 Visual Studio tooling has been modified to display the Add Controller menu item for any folder in your MVC project. This allows us to organize your controllers however you would like, perhaps separating them into logical groups or separating MVC and Web API controllers.

What are the software requirements of ASP.NET MVC4 application?
MVC 4 runs on the following Windows client operating systems:

  •     Windows XP
  •     Windows Vista
  •     Windows 7
  •     Windows 8
It runs on the following server operating systems:

  •     Windows Server 2003
  •     Windows Server 2008
  •     Windows Server 2008 R2
MVC 4 development tooling is included with Visual Studio 2012 and can be installed on Visual
Studio 2010 SP1/Visual Web Developer 2010 Express SP1.

What are the various types of Application Templates used to create an MVC application?
The various templates are as follows,

1. The Internet Application template: This contains the beginnings of an MVC web
application — enough so that you can run the application immediately after creating it
and see a few pages. This template also includes some basic account management functions which run against the ASP.NET Membership .

2. The Intranet Application template: The Intranet Application template was added as part of
the ASP.NET MVC 3 Tools Update. It is similar to the Internet Application template,but the account management functions run against Windows accounts rather than the ASP.NET Membership system.

3. The Basic template: This template is pretty minimal. It still has the basic folders, CSS, and
MVC application infrastructure in place, but no more. Running an application created using
the Empty template just gives you an error message.

Why use Basic template? The Basic template is intended for experienced MVC developers
who want to set up and configure things exactly how they want them.

4.The Empty template: The Basic template used to be called the Empty template, but developers complained that it wasn’t quite empty enough. With MVC 4, the previous Empty
template was renamed Basic, and the new Empty template is about as empty as we can get.
It has the assemblies and basic folder structure in place, but that’s about it.

5. The Mobile Application template: The Mobile Application template is preconfigured with jQuery Mobile to jump-start creating a mobile only website. It includes mobile visual themes, a touch-optimized UI, and support for Ajax navigation.

6. The Web API template: ASP.NET Web API is a framework for creating HTTP services.
The Web API template is similar to the Internet Application template but is streamlined for Web API development. For instance, there is no user account management functionality, as Web API account management is often signify-cantly different from standard MVC account management. Web API functionality is also available in the other MVC project templates, and even in non-MVC project types.

What are the default Top level directories created when adding MVC4 application?
Default Top level Directories are:
DIRECTORY           PURPOSE
/Controllers            To put Controller classes that handle URL requests
/Models                 To put classes that represent and manipulate data and business objects
/Views                   To put UI template files that are responsible for rendering output like HTML.
/Scripts                  To put JavaScript library files and scripts (.js)
/Images                  To put images used in your site
/Content                 To put CSS and other site content, other than scripts and images
/Filters                    To put filter code.
/App_Data             To store data files you want to read/write
/App_Start             To put configuration code for features like Routing, Bundling, Web API.

What is namespace of asp.net mvc?
ASP.NET MVC namespaces as well as classes are located in assembly System.Web.Mvc.

Note: Some of the content has been taken from various books/articles.

What is System.Web.Mvc namespace?
This namespace contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller
factories, action results, views, partial views, and model binders.

What is System.Web.Mvc.Ajax namespace?
System.Web.Mvc.Ajax namespace contains classes that supports Ajax scripting in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings as well.

What is System.Web.Mvc.Async namespace?
System.Web.Mvc.Async namespace contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application.

What is System.Web.Mvc.Html namespace?
System.Web.Mvc.Html namespace  contains classes that help render HTML controls in an MVC application. This namespace includes classes that support forms, input controls, links, partial views, and validation.

What is ViewData, ViewBag and TempData?
MVC provides us ViewData, ViewBag and TempData for passing data from controller, view and in next requests as well. ViewData and ViewBag are similar to some extent but TempData performs additional roles.

What are the roles and similarities between ViewData and ViewBag?
  • Maintains data when move from controller to view.
  • Passes data from controller to respective view.
  • Their value becomes null when any redirection occurs, because their role is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

What are the differences between ViewData and ViewBag?(taken from a blog)
  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • ViewData requires typecasting for complex data type and check for null values to avoid error.
  • ViewBag doesn’t require typecasting for complex data type.

NOTE Although there might not be a technical advantage to choosing one format over the other, there are some critical differences to be aware of between the two syntaxes.
One obvious difference is that ViewBag works only when the key being accessed is a valid C# identifier. For example, if you place a value in ViewData["KeyWith Spaces"], you can’t access that value using ViewBag because the codewon’t compile.

Another key issue to be aware of is that dynamic values cannot be passed in as parameters to extension methods. The C# compiler must know the real type of every parameter at compile time in order for it to choose the correct extension method.

If any parameter is dynamic, compilation will fail. For example, this code will always fail: @Html.TextBox("name", ViewBag.Name). To work around this,either use ViewData["Name"] or cast the value to a specifi c type: (string) ViewBag.Name.

What is TempData?
TempData is a dictionary derived from the TempDataDictionary class and stored in short lives session. It is a string key and object value.
It keep the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain data when we move from one controller to another controller or from one action to other action. In other words, when we redirect Tempdata helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when we are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. Generally it is used to store only one time messages like error messages, validation messages.

How can you define a dynamic property with the help of viewbag in ASP.NET MVC?
Assign a key name with syntax,
ViewBag.[Key]=[ Value] and value using equal to operator.
For example, you need to assign list of students to the dynamic Students property
of ViewBag.
List<string> students = new List<string>();
countries.Add("Akhil");
countries.Add("Ekta");
ViewBag.Students = students;
//Students is a dynamic property associated with ViewBag.

Note: Some of the content has been taken from various books/articles.

What is ViewModel(taken from stackoverflow)?

accepted
A view model represents data that you want to have displayed on your view/page.
Lets say that you have an Employee class that represents your employee domain model and it contains the following 4 properties:

public class Employee : IEntity
{
     public int Id { getset; }  // Employee's unique identifier
     public string FirstName { getset; }  // Employee's first name
     public string LastName { getset; }  // Employee's last name
     public DateTime DateCreated { getset; }  // Date when employee was created
}

View models differ from domain models in that view models only contain the data (represented by properties) that you want to use on your view. For example, lets say that you want to add a new employee record, your view model might look like this:
public class CreateEmployeeViewModel
{
     public string FirstName { getset; }
     public string LastName { getset; }
}

As you can see it only contains 2 of the properties of the employee domain model. Why is this you may ask? Id might not be set from the view, it might be auto generated by the Employee table. AndDateCreated might also be set in the stored procedure or in the service layer of your application. So Id and DateCreated is not need in the view model.
When loading the view/page, the create action method in your employee controller will create an instance of this view model, populate any fields if required, and then pass this view model to the view:
public class EmployeeController : Controller
{
     private readonly IEmployeeService employeeService;

     public EmployeeController(IEmployeeService employeeService)
     {
          this.employeeService = employeeService;
     }

     public ActionResult Create()
     {
          CreateEmployeeViewModel viewModel = new CreateEmployeeViewModel();

          return View(viewModel);
     }

     public ActionResult Create(CreateEmployeeViewModel viewModel)
     {
          // Do what ever needs to be done before adding the employee to the database
     }
}
Your view might look like this (assuming you are using ASP.NET MVC3 and razor):
@model MyProject.Web.ViewModels.ProductCreateViewModel

<table>
     <tr>
          <td><b>First Name:</b></td>
          <td>@Html.TextBoxFor(x => x.FirstNamenew { maxlength = "50", size = "50"})
              @Html.ValidationMessageFor(x => x.FirstName)
          </td>
     </tr>
     <tr>
          <td><b>Last Name:</b></td>
          <td>@Html.TextBoxFor(x => x.LastNamenew { maxlength = "50", size = "50"})
              @Html.ValidationMessageFor(x => x.LastName)
          </td>
     </tr>
</table>
Validation would thus be done only on FirstName and LastName. Using Fluent Validation you might have validation like this:
public class CreateEmployeeViewModelValidator :AbstractValidator<CreateEmployeeViewModel>
{
     public CreateEmployeeViewModelValidator()
     {
          RuleFor(x => x.FirstName)
               .NotEmpty()
               .WithMessage("First name required")
               .Length(150)
               .WithMessage("First name must not be greater than 50 characters");

          RuleFor(x => x.LastName)
               .NotEmpty()
               .WithMessage("Last name required")
               .Length(150)
               .WithMessage("Last name must not be greater than 50 characters");
     }
}
The key thing to remember is that the view model only represents the data that you want use. You can imagine all the uneccessary code and validation if you have a domain model with 30 properties and you only want to update a single value. Given this scenario you would only have this one value/property in the view model and not the whole domain object.

How do you check for AJAX request with C# in MVC.NET?
The solution is independed of MVC.NET framework and is global across server side
technologies. Most modern AJAX applications utilize XmlHTTPRequest to send
async request to the server. Such requests will have distinct request header:
X-Requested-With = XMLHTTPREQUEST



MVC.NET provides helper function to check for ajax requests which internally inspects
 X-Requested-With request header to set IsAjax flag.

What are Scaffold template?
These templates use the Visual Studio T4 templating system to generate a view based on the model type selected.Scaffolding in ASP.NET MVC can generate the boilerplate code we need for create, read, update,and delete (CRUD) functionality in an application. The scaffolding templates can examine the type definition for, and then generate a controller and the controller’s associated views. The scaffolding knows how to name controllers, how to name views, what code needs to go in each component, and where to place all these pieces in the project for the application to work.

What are the types of Scaffolding Templates?
Various types are as follows,
SCAFFOLD           DESCRIPTION
Empty                  Creates empty view. Only the model type is specified using the model syntax.
Create                  Creates a view with a form for creating new instances of the model.
                             Generates a label and input field for each property of the model type.
Delete                   Creates a view with a form for deleting existing instances of the model.
                             Displays a label and the current value for each property of the model.
Details                   Creates a view that displays a label and the value for each property of the
                             model type.
Edit                       Creates a view with a form for editing existing instances of the model.
                             Generates a label and input fi eld for each property of the model type.
List                       Creates a view with a table of model instances. Generates a column
                             for each property of the model type. Make sure to pass an IEnumerable<YourModelType> to this view from your action method.
                               The view also contains links to actions for performing the create/edit/delete                                                                                       operations.

Show an example of difference in syntax in Razor and WebForm View?
Razor <span>@model.Message</span>
Web Forms <span><%: model.Message %></span>
Code expressions in Razor are always HTML encoded. This Web Forms syntax also automatically HTML encodes the value.

What are Code Blocks in Views?
Unlike code expressions, which are evaluated and outputted to the response, blocks of code are simply sections of code that are executed. They are useful for declaring variables that we may need to use later.
Razor
@{
int x = 123;
string y = ˝because.˝;
}

Web Forms
<%
int x = 123;
string y = "because.";
%>

What is HelperPage.IsAjax Property?
HelperPage.IsAjax  gets a value that indicates whether Ajax is being used during the request of the Web page.
Namespace: System.Web.WebPages
Assembly: System.Web.WebPages.dll
However, same can be achieved by checking requests header directly:
Request["X-Requested-With"] == “XmlHttpRequest”.

Explain combining text and markup in Views with the help of an example?
This example shows what intermixing text and markup looks like using Razor as compared to Web Forms:

Razor
@foreach (var item in items) {
<span>Item @item.Name.</span>
}

Web Forms
<% foreach (var item in items) { %>
<span>Item <%: item.Name %>.</span>
<% } %>

Explain Repository Pattern in ASP.NET MVC?
In simple terms, a repository basically works as a mediator between our business logic layer and our data access layer of the application. Sometimes, it would be troublesome to expose the data access mechanism directly to business logic layer, it may result in redundant code for accessing data for similar entities or it may result in a code that is hard to test or understand. To overcome these kinds of issues, and to write an Interface driven and test driven code to access data, we use Repository Pattern. The repository makes queries to the data source for the data, thereafter maps the data from the data source to a business entity/domain object, finally and persists the changes in the business entity to the data source. According to MSDN, a repository separates the business logic from the interactions with the underlying data source or Web service. The separation between the data and business tiers has three benefits:
  • It centralizes the data logic or Web service access logic.
  • It provides a substitution point for the unit tests.
  • It provides a flexible architecture that can be adapted as the overall design of the application evolves.

In Repository, we write our whole business logic of CRUD operations with the help of Entity Framework classes, that will not only result in meaningful test driven code but will also reduce our controller code of accessing data.

How can you call a javascript function/method on the change of Dropdown List in MVC?
Create a java-script method:
<script type="text/javascript">
function selectedIndexChanged() {
}
</script>
Invoke the method:
<%:Html.DropDownListFor(x => x.SelectedProduct,
new SelectList(Model.Users, "Value", "Text"),
"Please Select a User", new { id = "ddlUsers",
onchange="selectedIndexChanged()" })%>

Explain Routing in MVC?
A route is a URL pattern that is mapped to a handler. The handler can be a physical
file, such as an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.
Routing within the ASP.NET MVC framework serves two main purposes:

  •       It matches incoming requests that would not otherwise match a file on the file system and maps the requests to a controller action.

  •       It constructs outgoing URLs that correspond to controller actions.

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

What are Layouts in ASP.NET MVC Razor?
Layouts in Razor help maintain a consistent look and feel across multiple views within our application.As compared to Web Forms Web Forms, layouts serve the same purpose as master pages, but offer both a simpler syntax and greater flexibility.
We can use a layout to define a common template for your site (or just part of it). This template contains one or more placeholders that the other views in your application provide content for. In some ways, it’s like an abstract base class for your views.
e.g. declared at the top of view as,
 @{
       Layout = "~/Views/Shared/SiteLayout.cshtml";
}

What is ViewStart?
For group of views that all use the same layout, this can get a bit redundant and harder to maintain.
The _ViewStart.cshtml page can be used to remove this redundancy. The code within this file
is executed before the code in any view placed in the same directory. This fi le is also recursively applied to any view within a subdirectory.
When we create a default ASP.NET MVC project, we find there is already a _ViewStart
.cshtml fi le in the Views directory. It specifi es a default layout:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Because this code runs before any view, a view can override the Layout property and choose a different one. If a set of views shares common settings, the _ViewStart.cshtml file is a useful place to consolidate these common view settings. If any view needs to override any of the common settings, the view can set those values to another value.

Note: Some of the content has been taken from various books/articles.

What are HTML Helpers?
HTML helpers are methods we can invoke on the Html property of a view. We also have
access to URL helpers (via the Url property), and AJAX helpers (via the Ajax property). All
these helpers have the same goal: to make views easy to author. The URL helper is also available from within the controller.
Most of the helpers, particularly the HTML helpers, output HTML markup. For example, the
BeginForm helper is a helper we can use to build a robust form tag for our search
form, but without using lines and lines of code:
@using (Html.BeginForm("Search", "Home", FormMethod.Get)) {
<input type="text" name="q" />
<input type="submit" value="Search" />
}

What is Html.ValidationSummary?
The ValidationSummary helper displays an unordered list of all validation errors in the ModelState dictionary. The Boolean parameter you are using (with a value of true) is telling the helper to exclude property-level errors. In other words, you are telling the summary to display only the errors in ModelState associated with the model itself, and exclude any errors associated with a specific model property. We will be displaying property-level errors separately.Assume you have the following code somewhere in the controller action rendering the edit view:
ModelState.AddModelError("", "This is all wrong!");
ModelState.AddModelError("Title", "What a terrible name!");
The first error is a model-level error, because you didn’t provide a key (or provided an empty key) to associate the error with a specifi c property. The second error you associated with the Title property, so in your view it will not display in the validation summary area (unless you remove the parameter to the helper method, or change the value to false). In this scenario, the helper renders the following HTML:

<div class="validation-summary-errors">
<ul>
<li>This is all wrong!</li>
</ul>
</div>

Other overloads of the ValidationSummary helper enable you to provide header text and set specific HTML attributes.
NOTE By convention, the ValidationSummary helper renders the CSS class validation-summary-errors along with any specifi c CSS classes you provide.The default MVC project template includes some styling to display these items in red, which you can change in styles.css.

What are Validation Annotations?
Data annotations are attributes you can find in System.ComponentModel.DataAnnotations
namespace.These attributes provide server-side validation, and the framework also supports client-side validation when you use one of the attributes on a model property. You can use four attributes in the DataAnnotations namespace to cover common validation scenarios,
Required, String Length, Regular Expression, Range.

What is Html.Partial?
The Partial helper renders a partial view into a string. Typically, a partial view contains reusable markup you want to render from inside multiple different views. Partial has four overloads:

public void Partial(string partialViewName);
public void Partial(string partialViewName, object model);
public void Partial(string partialViewName, ViewDataDictionary viewData);
public void Partial(string partialViewName, object model,
ViewDataDictionary viewData);

What is Html.RenderPartial?
The RenderPartial helper is similar to Partial, but RenderPartial writes directly to the response output stream instead of returning a string. For this reason, you must place RenderPartial inside a code block instead of a code expression. To illustrate, the following two lines of code render the same output to the output stream:
@{Html.RenderPartial("AlbumDisplay "); }
@Html.Partial("AlbumDisplay ")

If they are same then which one to use?
In general, you should prefer Partial to RenderPartial because Partial is more convenient (you don’t have to wrap the call in a code block with curly braces). However, RenderPartial may result in better performance because it writes directly to the response stream, although it would require a lot of use (either high site traffic or repeated calls in a loop) before the difference would be noticeable.

How do you return a partial view from controller?
return PartialView(options); //options could be Model or View name

What are different ways of returning a View?
There are different ways for returning/rendering a view in MVC Razor.E.g. return View(), return RedirectToAction(), return Redirect() and return RedirectToRoute().

Table of Contents
ASP.NET MVC Interview Questions and Answers .......................................... 1
Dedication ....................................................................................................................... 2
Introduction ..................................................................................................................... 3
About the author ............................................................................................................. 4
How to contact the author ............................................................................................... 5
ASP.NET MVC ................................................................................................ 10
Q1. What is MVC? .......................................................................................................................................... 10
Q2. Explain MVC design pattern? .................................................................................................................. 10
Q3. What is Domain Driven Design and Development? ................................................................................ 11
Q4. What is MVP pattern? ............................................................................................................................. 11
Q5. What is MVVM pattern? .......................................................................................................................... 12
Q6. What is ASP.NET MVC? ............................................................................................................................ 13
Q7. How MVC pattern works in ASP.NET MVC? ............................................................................................ 13
Q8. How Model, View and Controller communicate with each other in ASP.NET MVC? ............................. 14
Q9. What are advantages of ASP.NET MVC? ................................................................................................. 15
Q10. Explain brief history of ASP.NET MVC? ................................................................................................... 15
Q11. What is difference between 3-layer architecture and MVC architecture? ............................................. 17
Q12. What is difference between ASP.NET WebForm and ASP.NET MVC? .................................................... 17
Q13. What is ViewModel in ASP.NET MVC? .................................................................................................... 18
Q14. Explain ASP.NET MVC pipeline? .............................................................................................................. 18
Q15. What is Routing in ASP.NET MVC? .......................................................................................................... 21
Q16. How to define a route in ASP.NET MVC? ................................................................................................ 22
Q17. What is Attribute Routing and how to define it? .................................................................................... 23
Q18. When to use Attribute Routing? ............................................................................................................. 24
Q19. How to enable Attribute Routing in ASP.NET MVC? ............................................................................... 24
Q20. How to define Attribute Routing for Area in ASP.NET MVC? .................................................................. 25
Q21. What is difference between Routing and URL Rewriting? ...................................................................... 26
Q22. What is Route Constraints in ASP.NET MVC? .......................................................................................... 26 Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 7

Q23. How route table is created in ASP.NET MVC? ......................................................................................... 27
Q24. What are important namespaces in ASP.NET MVC? ............................................................................... 27
Q25. What is View Engine? .............................................................................................................................. 27
Q26. How View Engine works? ........................................................................................................................ 27
Q27. What is Razor View Engine? .................................................................................................................... 27
Q28. How to make Custom View Engine? ........................................................................................................ 28
Q29. How to register Custom View Engine in ASP.NET MVC? ......................................................................... 29
Q30. Can you remove default View Engine in ASP.NET MVC? ........................................................................ 29
Q31. What is difference between Razor and WebForm engine? .................................................................... 29
Q32. What are HTML Helpers in ASP.NET MVC? ............................................................................................. 30
Q33. What are different types of HTML Helpers? ........................................................................................... 30
Q34. What are Url Helpers? ............................................................................................................................. 34
Q35. What is Validation Summary? ................................................................................................................. 34
Q36. What are AJAX Helpers? .......................................................................................................................... 35
Q37. What is unobtrusive AJAX? ...................................................................................................................... 35
Q38. What are various configuration options for AJAX Helpers? .................................................................... 35
Q39. What is Cross Domain AJAX? ................................................................................................................... 36
Q40. What are Layouts in ASP.NET MVC?........................................................................................................ 36
Q41. What are Sections in ASP.NET MVC?....................................................................................................... 37
Q42. What are RenderBody and RenderPage in ASP.NET MVC? ..................................................................... 37
Q43. What are Styles.Render and Scripts.Render? .......................................................................................... 37
Q44. How to enable and disable optimizations in ASP.NET MVC? .................................................................. 38
Q45. What is ViewStart? .................................................................................................................................. 38
Q46. When to use ViewStart? .......................................................................................................................... 38
Q47. What are different ways of rendering layout in ASP.NET MVC? ............................................................. 39
Q48. What is App_Start folder in ASP.NET MVC? ............................................................................................ 40
Q49. What are different ways of returning/rendering a view in ASP.NET MVC? ............................................ 40
Q50. What are differences among ViewData, ViewBag, TempData and Session? .......................................... 41
Q51. How to persist data in TempData? .......................................................................................................... 42
Q52. How to control Session behavior in ASP.NET MVC? ................................................................................ 43
Q53. How TempData is related to Session in ASP.NET MVC? .......................................................................... 44
Q54. What are Action methods in ASP.NET MVC? .......................................................................................... 44 Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 8

Q55. What is ActionResult and how is it different from others? ..................................................................... 45
Q56. How to make a Non-Action method in ASP.NET MVC? ........................................................................... 45
Q57. Can you change action method name? ................................................................................................... 45
Q58. How to restrict an action method to be invoked only by HTTP GET, POST, PUT or DELETE? ................. 46
Q59. How to determine an action method is invoked by HTTP GET or POST? ................................................ 46
Q60. How to determine an AJAX request? ...................................................................................................... 47
Q61. What is Data Annotations in ASP.NET MVC? .......................................................................................... 47
Q62. How to apply Server side validation in ASP.NET MVC? ........................................................................... 47
Q63. How to determine there is no error in Model State? .............................................................................. 49
Q64. How to enable and disable client-side validation in ASP.NET MVC? ...................................................... 49
Q65. What is a CDN and advantages of CDN? ................................................................................................. 49
Q66. What is jquery.validate.unobtrusive.js? .................................................................................................. 50
Q67. What is Bundling and Minification in ASP.NET MVC? ............................................................................. 50
Q68. Can we use Bundling and Minification in ASP.NET MVC3 or ASP.NET4.0? ............................................. 52
Q69. How Bundling use browser Cache capability? ......................................................................................... 52
Q70. What is Partial View in ASP.NET MVC? ................................................................................................... 52
Q71. How do you return a partial view from controller? ................................................................................ 53
Q72. What are different ways of rendering a Partial View in ASP.NET MVC? ................................................. 53
Q73. What is Area in ASP.NET MVC? ............................................................................................................... 54
Q74. How to register Area in ASP.NET MVC? .................................................................................................. 55
Q75. What is Child action and how to invoke it? ............................................................................................. 55
Q76. What is Scaffolding? ................................................................................................................................ 55
Q77. How Scaffold templates works in ASP.NET MVC? ................................................................................... 55
Q78. What are ASP.NET MVC Filters and Attributes? ...................................................................................... 57
Q79. What are different types of Filters in ASP.NET MVC? ............................................................................. 58
Q80. What is the order of execution of filters in ASP.NET MVC? .................................................................... 60
Q81. When Exception filters are executed in ASP.NET MVC? ......................................................................... 60
Q82. How to configure filters in ASP.NET MVC? .............................................................................................. 60
Q83. How Authentication and Authorization work in ASP.NET MVC? ............................................................ 61
Q84. How Forms Authentication and Authorization work in ASP.NET MVC? ................................................. 61
Q85. How to implement custom Forms Authentication and Authorization in MVC? ..................................... 62
Q86. How to allow HTML tags in ASP.NET MVC? ............................................................................................. 65 Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 9

Q87. What is caching and when to use it? ....................................................................................................... 66
Q88. What are advantages of caching? ........................................................................................................... 66
Q89. What is output caching? .......................................................................................................................... 66
Q90. What is Donut caching and Donut hole caching in ASP.NET MVC? ........................................................ 67
Q91. What is loose coupling and how is it possible? ....................................................................................... 68
Q92. What are Dependency Inversion Principle (DIP) and IoC? ...................................................................... 68
Q93. What is Dependency Injection (DI)? ........................................................................................................ 69
Q94. What is Service Locator? ......................................................................................................................... 70
Q95. What are different ways to implement Dependency Injection (DI)? ...................................................... 72
Q96. What are advantages of Dependency Injection (DI)? ............................................................................. 75
Q97. What is IoC or DI container? .................................................................................................................... 75
Q98. What are popular DI containers? ............................................................................................................ 75
Q99. What is Test Driven Development (TDD)? ............................................................................................... 76
Q100. What are commonly used tool for Unit Testing in ASP.NET MVC? ..................................................... 76
ASP.NET WEB API.......................................................................................... 77
Q1. What is REST? .......................................................................................................................................... 77
Q2. Explain REST principle? ............................................................................................................................ 77
Q3. What is difference between REST and SOAP? ......................................................................................... 77
Q4. What is ASP.NET WEB API? ..................................................................................................................... 78
Q5. Why to choose ASP.NET WEB API? .......................................................................................................... 78
Q6. What is difference between WCF and WEB API and WCF REST and Web Service? ................................ 79
Q7. Which one to choose between WCF and WEB API?................................................................................ 80
Q8. What is difference between ASP.NET MVC and ASP.NET WEB API?....................................................... 81
Q9. Can you return view by using WEB API method? .................................................................................... 81
Q10. Can you change WEB API action name like ASP.NET MVC? .................................................................... 82
Q11. Can you restrict a WEB API action method to be invoked only by HTTP GET, POST, PUT or DELETE? ... 82
Q12. How to call WEB API in ASP.NET MVC? ................................................................................................... 82
Q13. How ASP.NET WEB API routing is different from ASP.NET MVC routing? .............................................. 83
Q14. How to enable Attribute Routing in ASP.NET WEB API2? ....................................................................... 83
Q15. How to define attribute routing in ASP.NET WEB API2? ......................................................................... 83 Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 10

1
ASP.NET MVC
Q1. What is MVC?
Ans. MVC stands for Model-View-Controller. It is a software design pattern which was introduced in 1970s. Also, MVC pattern forces a separation of concerns, it means domain model and controller logic are decoupled from user interface (view). As a result maintenance and testing of the application become simpler and easier.
Q2. Explain MVC design pattern?
Ans. MVC design pattern splits an application into three main aspects: Model, View and Controller
Model - The Model represents a set of classes that describe the business logic i.e. business model as well as data access operations i.e. data model. It also defines business rules for data means how the data can be changed and manipulated.
View - The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the controller as the result. This also transforms the model(s) into UI.
Controller - The Controller is responsible to process incoming requests. It receives input from users via the View, then process the user's data with the help of Model and passing the results back to the View. Typically, it acts as the coordinator between the View and the Model. Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 11

Today, this pattern is used by many popular framework like as Ruby on Rails, Spring Framework, Apple iOS Development and ASP.NET MVC.
Q3. What is Domain Driven Design and Development?
Ans. Domain-Driven Design (DDD) is a collection of principles and patterns that help developers to take design decisions to develop elegant systems for different domains. It is not a technology or methodology.
The main components of DDD are: Entity, Value Object, Aggregate, Service and Repository.
Entity- An object that has an identity- it is unique within the system, like Customer, Employee etc.
Value Object- An object that has no identity within the system like Rate, State etc.
Note: A value object can become an entity depending on the situation.
Aggregate: An aggregate root is a special kind of entity that consumers refer to directly. All consumers of the aggregate root are called as aggregate. The aggregate root guarantees the consistency of changes being made within the aggregate.
Service- A service is a way of dealing with actions, operations and activities within your application.
Repository- A repository is responsible to store and to retrieve your data. It is not a concern how and where data will be persist. So, it can be SQL server, oracle, xml, text file or anything else. Repository is not a Data Access Layer but it refers to a location for storage, often for safety or preservation.
For more info refer this link http://msdn.microsoft.com/en-us/magazine/dd419654.aspx
Q4. What is MVP pattern?
Ans. This pattern is similar to MVC pattern in which controller has been replaced by the presenter. This design pattern splits an application into three main aspects: Model, View and Presenter.
Model - The Model represents a set of classes that describes the business logic and data. It also defines business rules for data means how the data can be changed and manipulated.
View - The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the presenter as the result. This also transforms the model(s) into UI.
Presenter - The Presenter is responsible for handling all UI events on behalf of the view. This receive input from users via the View, then process the user's data with the help of Model and passing the results back to the View. Unlike view and controller, view and presenter are completely decoupled from each other’s and communicate to each other’s by an interface.
Also, presenter does not manage the incoming request traffic as controller. Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 12

This pattern is commonly used with ASP.NET Web Forms applications which require to create automated unit tests for their code-behind pages. This is also used with windows forms.
Key Points about MVP Pattern
1. User interacts with the View.
2. There is one-to-one relationship between View and Presenter means one View is mapped to only one Presenter.
3. View has a reference to Presenter but View has not reference to Model.
4. Provides two way communication between View and Presenter.

Q5. What is MVVM pattern?
Ans. MVVM stands for Model-View-View Model. This pattern supports two-way data binding between view and View model. This enables automatic propagation of changes, within the state of view model to the View. Typically, the view model uses the observer pattern to notify changes in the view model to model.
Model - The Model represents a set of classes that describes the business logic and data. It also defines business rules for data means how the data can be changed and manipulated.
View - The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the controller as the result. This also transforms the model(s) into UI.
View Model - The View Model is responsible for exposing methods, commands, and other properties that helps to maintain the state of the view, manipulate the model as the result of actions on the view, and trigger events in the view itself. Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 13

This pattern is commonly used by the WPF, Silverlight, Caliburn, nRoute etc.
Key Points about MVVM Pattern
1. User interacts with the View.
2. There is many-to-one relationship between View and ViewModel means many View can be mapped to one ViewModel.
3. View has a reference to ViewModel but View Model has no information about the View.
4. Supports two-way data binding between View and ViewModel.

Q6. What is ASP.NET MVC?
Ans. ASP.NET MVC is an open source framework built on the top of Microsoft .NET Framework to develop web application that enables a clean separation of code. ASP.NET MVC framework is the most customizable and extensible platform shipped by Microsoft.
Q7. How MVC pattern works in ASP.NET MVC?
Ans. Working of MVC pattern in ASP.NET MVC is explained as below:
The Model in ASP.NET MVC
The Model in ASP.NET MVC can be broken down into several different layers as given below:
1. Objects or ViewModel or Presentation Layer - This layer contains simple objects or complex objects which are used to specify strongly-typed view. These objects are used to pass data from controller to strongly-typed view and vice versa. The classes for these objects can have specific validation rules which are defined by using data annotations. Typically, these classes have those properties which you want to display on corresponding view/page.

2. Business Layer - This layer helps you to implement your business logic and validations for your application. This layer make use of Data Access Layer for persisting data into database. Also, this layer is directly invoked by the Controller to do processing on input data and sent back to view.
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 14


3. Data Access Layer - This layer provides objects to access and manipulate the database of your application. Typically, this layer is made by using ORM tools like Entity Framework or NHibernate etc.

By default, models are stored in the Models folder of an ASP.NET MVC application.
The View in ASP.NET MVC
The view is only responsible for displaying the data that is received from the controller as a result. It also responsible for transforming a model or models into UI which provide all the required business logic and validation to the view.
By default, views are stored in the Views folder of an ASP.NET MVC application.
The Controller in ASP.NET MVC
The Controller in ASP.NET MVC, respond to HTTP requests and determine the action to take based upon the content of the incoming request. It receives input from users via the View, then process the user's data with the help of Model and passing the results back to the View.
By default, controllers are stored in the Controllers folder an ASP.NET MVC application.
Q8. How Model, View and Controller communicate with each other in ASP.NET MVC?
Ans. There are following rules for communication among Model, View and Controller:
1. User interacts with the Controller.
2. There is one-to-many relationship between Controller and View means one controller can mapped to multiple views.
3. Controller and View can have a reference to model.
4. Controller and View can talk to each other.
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 15


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

Q9. What are advantages of ASP.NET MVC?
Ans. There are following advantages of ASP.NET MVC over Web Forms (ASP.NET):
Separation of concern - MVC design pattern divides the ASP.NET MVC application into three main aspects Model, View and Controller which make it easier to manage the application complexity.
TDD - The MVC framework brings better support to test-driven development.
Extensible and pluggable - MVC framework components were designed to be pluggable and extensible and therefore can be replaced or customized easier then Web Forms.
Full control over application behaviour - MVC framework doesn’t use View State or server based forms like Web Forms. This gives the application developer more control over the behaviors of the application and also reduces the bandwidth of requests to the server.
ASP.NET features are supported - MVC framework is built on top of ASP.NET and therefore can use most of the features that ASP.NET include such as the providers architecture, authentication and authorization scenarios, membership and roles, caching, session and more.
URL routing mechanism - MVC framework supports a powerful URL routing mechanism that helps to build a more comprehensible and searchable URLs in your application. This mechanism helps to the application to be more addressable from the eyes of search engines and clients and can help in search engine optimization.

Q10. Explain brief history of ASP.NET MVC?
Ans. Here is the list of released version history of ASP.NET MVC Framework with theirs features.
ASP.NET MVC1
 Released on Mar 13, 2009
 Runs on .NET 3.5 and with Visual Studio 2008 & Visual Studio 2008 SP1
 MVC Pattern architecture with WebForm Engine
 Html Helpers
 Ajax helpers
 Routing
 Unit Testing

ASP.NET MVC2
 Released on Mar 10, 2010
 Runs on .NET 3.5, 4.0 and with Visual Studio 2008 & 2010
 Strongly typed HTML helpers means lambda expression based Html Helpers
 Templated Helpers
 UI helpers with automatic scaffolding & customizable templates
 Support for DataAnnotations Attributes to apply model validation on both client and server sides
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 16


 Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE
 Areas for partitioning a large applications into modules
 Asynchronous controllers

ASP.NET MVC3
 Released on Jan 13, 2011
 Runs on .NET 4.0 and with Visual Studio 2010
 The Razor view engine
 Enhanced Data Annotations attributes for model validation on both client and server sides
 Remote Validation
 Compare Attribute
 Session less Controller
 Child Action Output Caching
 Dependency Resolver
 Entity Framework Code First support
 Partial-page output caching
 ViewBag dynamic property for passing data from controller to view
 Global Action Filters
 Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
 Use of NuGet to deliver software and manage dependencies throughout the platform

ASP.NET MVC4
 Released on Aug 15, 2012
 Runs on .NET 4.0, 4.5 and with Visual Studio 2010SP1 & Visual Studio 2012
 ASP.NET WEB API
 Enhancements to default project templates
 Mobile project template using jQuery Mobile
 Display Modes
 Task support for Asynchronous Controllers
 Bundling and minification
 Support for the Windows Azure SDK

ASP.NET MVC5
 Released on 17 October 2013
 Runs on .NET 4.5, 4.5.1 and with Visual Studio 2012 & Visual Studio 2013
 One ASP.NET
Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 17


 ASP.NET Identity
 ASP.NET Scaffolding
 Authentication filters - run prior to authorization filters in the ASP.NET MVC pipeline
 Bootstrap in the MVC template
 ASP.NET WEB API2

Q11. What is difference between 3-layer architecture and MVC architecture?
Ans. 3-layer architecture separates the application into 3 components which consists of Presentation Layer Business Layer and Data Access Layer. In 3-layer architecture, user interacts with the Presentation layer. 3-layer is a linear architecture.
MVC architecture separates the application into three components which consists of Model, View and Controller. In MVC architecture, user interacts with the controller with the help of view. MVC is a triangle architecture.
MVC does not replace 3-layer architecture. Typically 3-layer and MVC are used together and MVC acts as the Presentation layer.
Q12. What is difference between ASP.NET WebForm and ASP.NET MVC?
Ans. The main differences between ASP.NET Web Form and ASP.NET MVC are given below: ASP.NET Web Forms
ASP.NET MVC
ASP.NET Web Form follows a traditional event driven development model.
ASP.NET MVC is a lightweight and follow MVC (Model, View, and Controller) pattern based development model.
ASP.NET Web Form has server controls.
ASP.NET MVC has html helpers.


ASP.NET MVC  - Some Frequently Asked Questions
This article introduces ASP.NET MVC and answers some frequently asked questions about ASP.NET WebForms vs ASP.NET MVC. 
What is MVC?
MVC or the Model-View-Controller is an architectural pattern used in software engineering for separating the components of a Web application. The MVC pattern helps decouple the business logic from the presentation layer which in turn gives you the flexibility to make changes to a layer, without affecting the other. This also leads to effective testing and maintainability.
The implementation of this pattern is divided into three parts:
-          Model – Represents the domain specific data
-          View – UI Components responsible to display the Model data
-          Controller – Handles User Interactions/Events, manipulates and updates the model to reflect a change in the state of an application.
What is ASP.NET MVC?
ASP.NET MVC is a web development framework that embraces the MVC architecture. It is a part of the ASP.NET framework and provides an alternative way to develop ASP.NET Web applications.
Microsoft started working on the ASP.NET MVC framework in October 2007 and after a series of Previews and Beta Releases, ASP.NET MVC 1.0 was released on 17th March 2009. As of this writing, ASP.NET MVC 2 Preview 1 has been released
How is ASP.NET MVC different from ASP.NET WebForms (ASP.NET WebForm VS ASP.NET MVC)? Is ASP.NET MVC a replacement for WebForms?
No. ASP.NET MVC, is not a replacement for WebForms. Both ASP.NET MVC and ASP.NET WebForms are built on top of the Core ASP.NET Framework. In fact a lot of features we use in ASP.NET such as Roles, Membership, Authentication and a lot of namespaces, classes and interfaces can be used in an ASP.NET MVC application
Here are some points that differentiate ASP.NET WebForms from ASP.NET MVC:
ASP.NET WebForms
ASP.NET MVC
Uses the ‘Page Controller’ pattern. Each page has a code-behind class that acts as a controller and is responsible for rendering the layout.
Uses the ‘Front Controller’ pattern. There is a single central controller for all pages to process web application requests and facilitates a rich routing architecture
Uses an architecture that combines the Controller (code behind) and the View (.aspx). Thus the Controller has a dependency on the View. Due to this, testing and maintainability becomes an issue.
ASP.NET MVC enforces a "separation of concerns". The Model does not know anything about the View. The View does not know there’s a Controller. This makes MVC applications easier to test and maintain.
The View is called before the Controller.
Controller renders View based on actions as a result of the User Interactions on the UI.
At its core, you ‘cannot’ test your controller without instantiating a View. There are ways to get around it using tools.
At its core, ASP.NET MVC was designed to make test-driven development easier. You ‘can’ test your Controller without instantiating a View and carry out unit-tests without having to run the controllers in an ASP.NET process.
WebForms manage state by using view state and server-based controls.
ASP.NET MVC does not maintain state information by using view state.
WebForms supports an event-driven programming style that is like Windows applications and is abstracted from the user. The State management is made transparent by using sessions, viewstate etc. In the process, the HTML output is not clean making it difficult to manage later. The ViewState also increases your page size.
In ASP.NET MVC, the output is clean and you have full control over the rendered HTML. The orientation is towards building standard compliant pages and provides full control over the behavior of an application.
Deep understanding of HTML, CSS and JavaScript is not required to a large extent since the WebForm model abstracts a lot of these details and provides automatic plumbing. While abstracting details to provide ease of use, sometimes a solution is overcomplicated, than it needs to be.
A thorough understanding of how HTML, CSS and JavaScript work together is required. The advantage is you can do a lot of jQuery and AJAX stuff in an efficient and simple manner than you would do in an ASP.NET application.
WebForms can drastically reduce time while building up intranet and internet applications that use a lot of controls (drag and drop model). Although this is true for development, a lot of time is spent later to code around limitations.
You lose the 'drag and drop' quick model of building your web applications. The focus is on control over the application behavior and test-driven development. The model is extensible and you do not have to spend time working around limitations.
Relatively simple to learn and pickup. Works very well for developers who initially have trouble with the HTTP/HTML model and are coming from a similar WinForms oriented event model.
There is a learning curve to understand the why, when and how of ASP.NET MVC.
Lesser amount of code is required to build webapps since a lot of components are integrated and provided out of the box. You can also use a lot of data controls provided out of the box that rely on ViewState.
Since the application tasks are separated into different components, amount of code required is more. Since ASP.NET MVC does not use ViewState, you cannot use Data controls like GridView, Repeater.
Works very well for small teams where focus is on rapid application development
Works well for large projects where focus in on testability and maintainability.
 Remember there is always a trade-off in adopting a certain technology. We also cannot conclude that one model is better than the other. You need to decide upon various factors and do a thorough feasibility study before you go in for a certain methodology of developing your applications. Use the tool best suited for the job. You do not have to do something just because others are doing it!
I would like to quote Rex Morgan as he put this point brilliantly in the stackoverflow forums.
“It's important to keep in mind that MVC and WebForms are not competing, and one is not better than the other. They are simply different tools. Most people seem to approach MVC vs WebForms as "one must be a better hammer than the other". That is wrong. One is a hammer, the other is a screwdriver. Both are used in the process of putting things together, but have different strengths and weaknesses.
If one left you with a bad taste, you were probably trying to use a screwdriver to pound a nail. Certain problems are cumbersome with WebForms that become elegant and simple with MVC, and vice-versa”
I find ASP.NET WebForms easier. When and Why should I Care about ASP.NET MVC?
Again, ASP.NET MVC is not introduced to replace WebForms. WebForms has been amazing in its own arena, but depending on your experiences with it and how far have you have exploited it’s usage in your applications, there are difference of opinions as far as its advantages and disadvantages are concerned.
Here are some points that will help you understand and embrace ASP.NET MVC.
ASP.NET MVC is for you if you –
-          care to build applications that are maintainable, testable and are ‘abreast’ with the other development methodologies, a couple of years from now.
-          emphasize on reducing complexity by enforcing ‘separation of concerns’ and introducing loose coupling. Tasks are separated and handled by separate components.
-          are tired of dealing with postback and viewstate issues
-          choose testability (Test Driven Development) over rapid application development(rad) where in rad, a single class is responsible for displaying output and responding to events. This behavior couples the layers tightly, making it difficult to test.
-          have a large team of developers and want to promote parallel development where there are separate teams working on the view, controller and model.
-          want to provide your application with multiple user interface. Since there is no or little dependency between different components, you can adopt a pluggable UI model in your application keeping the same business components.
-          are worried that your smart-client look-a-like, tightly coupled and stateful abstracted webform model is difficult to test and breaks frequently while maintaining application.
-          want a simple, seamless and maintainable AJAX experience like other platforms provide
-          want meaningful, RESTful URL’s
-          need to work on multiple platforms later. A shift from ASP.NET MVC to Ruby on Rails and other similar platforms is easier. It’s also a good option to consider for your career.
My advice to all you developers out there would be to go ahead and pick up this new technology, develop a sample MVC project and you will soon realize that you are following architectural best practices, are closer to the way web works and are using AJAX and JQuery efficiently to deliver jaw dropping UI experiences. A lot of our development time has gone in measuring the height and width in your apps – it’s now time to take a dive into the depth of it and see how things are done the right way – the web oriented way. After all, we will be trying a framework based on a pattern that has been used for over 30 years now! So the ‘it will work’ tests have been done for us.
I am still doubtful. How will companies adopt ASP.NET MVC ?

Now that’s a tricky question. There is an investment required here in terms of resources and adopting a new technology. With the economy on a downtrend, the adaptability will be slower initially than Microsoft would have expected. Since both the frameworks, ASP.NET WebForms and ASP.NET MVC, are a product of the same company, it will be the client’s need and the project’s interest that will drive the show. As I said, it’s a tricky question!
Where can I download ASP.NET MVC from? Is it Free?
Yes, ASP.NET MVC is absolutely free. You can download ASP.NET MVC 1.0 from here
As of this writing, ASP.NET MVC 2 Preview 1 has been released which can be downloaded from hereThe latest version is ASP.NET MVC 4 and it can be downloaded here http://www.asp.net/mvc
Does Microsoft have a Roadmap for ASP.NET MVC? Is Microsoft keen on taking this ahead?
There is an ASP.NET MVC Roadmap. The ASP.NET MVC framework is well maintained well documented and there are plenty of tutorials, videos and hands on labs available. There is a clear roadmap too. I feel this framework is here to stay and it will be fun watching how this architecture evolves with ASP.NET over the period of time.
What about Migration from one to the other? Can we also create an Application using ASP.NET WebForms and ASP.NET MVC?
In some cases, Yes. I would say that both the technologies complement each other, but migrating from WebForms to ASP.NET MVC will not be a piece of cake depending on the size of the projects. People, who are keen to use WebForms only and focus only on separation of the logic and UI, can adopt the MVP Pattern. However the MVP pattern is not as effective as the MVC.
If you are planning on developing an ASP.NET WebForms application and plan to move it to ASP.NET MVC in future, then try to build a loosely coupled architecture. This way the pains of migrating will be less. Moreover since ASP.NET MVC focuses on plugability and can be extended, functionality like Routing can be used in ASP.NET WebForms and the same can be utilized in ASP.NET MVC later.
Honestly, although I have not yet built an application that involves both ASP.NET WebForms and ASP.NET MVC, it does look possible to build one, since both the technologies are built on top of the core ASP.NET framework.
What is the best way to learn ASP.NET MVC?
Start using it! There are some additional resources, learning tutorials and articles listed over here that makes the learning curve smoother –
-          Official ASP.NET MVC Site
-          Learn ASP.NET MVC – ASP.NET MVC Written Tutorials, Video Tutorials, Sample Applications
-          ASP.NET MVC Training Kit - hands-on-labs, demos, decks, FAQs, etc
-          Rob Conery’s MVC StoreFront Series – In Rob’s own words, the goal of the series is to explore ASP.NET MVC and the various disciplines that compliment it. Rob has  covered all kinds of developer goodness, including Test-driven Development, Dependency Injection, and (lightly) Domain Driven Design in these series.
-          ASP.NET MVC documentation – documentation of the public namespaces, classes, and interfaces that support ASP.NET MVC
-          Professional ASP.NET MVC 1.0  – A great book by Rob Conery, Scott Hanselman, Phil Haack and Scott Gutherie begins with a complete ASP.NET MVC reference application and then takes you through the basic and advanced features of ASP.NET MVC.

No comments:

Post a Comment

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...