Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 195

1. Explain MVC (Model-View-Controller) in general?

MVC (Model-View-Controller) is an architectural software pattern that basically decouples various


components of a web application. By using MVC pattern, we can develop applications that are more
flexible to changes without affecting the other components of our application.

 “Model”, is basically domain data.


 “View”, is user interface to render domain data.
 “Controller”, translates user actions into appropriate operations performed on model.

2. What is ASP.NET MVC?

ASP.NET MVC is a web development framework from Microsoft that is based on MVC (Model-View-
Controller) architectural design pattern. Microsoft has streamlined the development of MVC based
applications using ASP.NET MVC framework.

3. Difference between ASP.NET MVC and ASP.NET WebForms?

ASP.NET Web Forms uses Page controller pattern approach for rendering layout, whereas ASP.NET
MVC uses Front controller approach. In case of Page controller approach, every page has its own
controller i.e. code-behind file that processes the request. On the other hand, in ASP.NET MVC, a
common controller for all pages processes the requests.
4. What are the Core features of ASP.NET MVC?

Core features of ASP.NET MVC framework are:

 Clear separation of application concerns (Presentation and Business Logic). It reduces


complexity that makes it ideal for large scale applications where multiple teams are working.
 It’s an extensible as well as pluggable framework. We can plug components and further
customize them easily.
 It provides extensive support for URL Routing that helps to make friendly URLs (means friendly
for human as well as Search Engines).
 It supports for Test Driven Development (TDD) approach. In ASP.NET WebForms, testing
support is dependent on Web Server but ASP.NET MVC makes it independent of Web Server,
database or any other classes.
 Support for existing ASP.NET features like membership and roles, authentication and
authorization, provider model and caching etc.

5. Can you please explain the request flow in ASP.NET MVC framework?

Request flow for ASP.NET MVC framework is as follows:

Request hits the controller coming from client. Controller plays its role and decides which model to use in
order to serve the request. Further passing that model to view which then transforms the model and
generate an appropriate response that is rendered to client.

6. What is Routing in ASP.NET MVC?

In case of a typical ASP.NET application, incoming requests are mapped to physical files such as .aspx
file. On the other hand, ASP.NET MVC framework uses friendly URLs that more easily describe user’s
action but not mapped to physical files. Let’s see below URLs for both ASP.NET and ASP.NET MVC.

//ASP.NET approach – Pointing to physical files (Student.aspx)

//Displaying all students

http://locahost:XXXX/Student.aspx
//Displaying a student by Id = 5

http://locahost:XXXX/Student.aspx?Id=5

//ASP.NET MVC approach – Pointing to Controller i.e. Student

//Displaying all students

http://locahost:XXXX/Student

//Displaying student by Id = 5

http://locahost:XXXX/Student/5/

ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can define
routing rules for the engine, so that it can map incoming request URLs to appropriate controller.
Practically, when a user types a URL in a browser window for an ASP.NET MVC application and presses
“go” button, routing engine uses routing rules that are defined in Global.asax file in order to parse the
URL and find out the path of corresponding controller.

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

In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework
provides different options i.e. ViewData, ViewBag and TempData.

Both ViewBag and ViewData are used to communicate between controller and corresponding view. But
this communication is only for server call, it becomes null if redirect occurs. So, in short, its a mechanism
to maintain state between controller and corresponding view. ViewData is a dictionary object while
ViewBag is a dynamic property (a new C# 4.0 feature). ViewData being a dictionary object is accessible
using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag
doesn’t have typecasting and null checks.

TempData is also a dictionary object that stays for the time of an HTTP Request. So, TempData can be
used to maintain data between redirects i.e from one controller to the other controller.
8. What are Action Methods in ASP.NET MVC?

As I already explained about request flow in ASP.NET MVC framework that request coming from client
hits controller first. Actually MVC application determines the corresponding controller by using routing
rules defined in Global.asax. And controllers have specific methods for each user actions. Each request
coming to controller is for a specific Action Method. The following code sample, “ShowBook” is an
example of an Action Method.

public ViewResult ShowBook(int id)

var computerBook = db.Books.Where(p => P.BookID == id).First();

return View(computerBook);

Action methods perform certain operation using Model and return result back to View. As in above
example, ShowBook is an action method that takes an Id as input, fetch specific book data and returns
back to View as ViewResult. In ASP.NET MVC, we have many built-in ActionResults type:

 ViewResult

 PartialViewResult

 RedirectResult

 RedirectToRouteResult

 ContentResult

 JsonResult

 EmptyResult

 and many more….

Important Note: All public methods of a Controller in ASP.NET MVC framework are considered to be
Action Methods by default. If we want our controller to have a Non Action Method, we need to explicitly
mark it with NonAction attribute as follows:

[NonAction]

public void MyNonActionMethod() { ….. }

9.Explain the role of Model in ASP.NET MVC?

One of the core feature of ASP.NET MVC is that it separates the input and UI logic from business logic.
Role of Model in ASP.NET MVC is to contain all application logic including validation, business and
data access logic except view i.e. input and controller i.e UI logic.
Model is normally responsible for accessing data from some persistent medium like database and
manipulate it, so you can expect that interviewer can ask questions on database access topics here along
with ASP.NET MVC Interview Questions.

10.What are Action Filters in ASP.NET MVC?

If we need to apply some specific logic before or after action methods, we use action filters. We can apply
these action filters to a controller or a specific controller action. Action filters are basically custom classes
that provide a mean for adding pre-action or post-action behavior to controller actions For example,

 Authorize filter can be used to restrict access to a specific user or a role.

 OutputCache filter can cache the output of a controller action for a specific duration.

 and more…

Top ASP.NET MVC Online Courses

 Learn ASP NET MVC 5 step by step [Maruti Makwana, Corporate Trainer] 28 Lectures, 2.5
Hours Video, Intermediate Level

Very easy to learn video series on Asp.Net MVC 5 Specially for those who are familiar with Asp.Net
Web forms.

 AngularJS for ASP.NET MVC Developers [Brett Romero] 10 Lectures, 1 hour video,
Intermediate Level

The Fastest Way For .NET Developers To Add AngularJS To Their Resume

 ASP.NET with Entity Framework from Scratch [Manzoor Ahmad, MCPD | MCT] 77 Lectures,
10 hour video, All Level

Latest approach of web application development

 Comprehensive ASP.NET MVC [3D BUZZ] 34 lectures, 14 Hours Video, All Levels

From zero knowledge of ASP.NET to deploying a complete project to production.

More Interview Questions on ASP.NET MVC

What are the new features introduced in ASP.NET MVC5?

ASP.NET MVC5 was introduced with following exciting features:

 ASP.NET Identity

 Authentication Filters
 Filter Overrides

 Scaffolding

 Bootstrap

 Attribute Routing

What is a ViewEngine in ASP.NET MVC?

“View Engine in ASP.NET MVC is used to translate our views to HTML and then render to browser.”

There are few View Engines available for ASP.NET MVC but commonly used View Engines are Razor,
Web Forms/ASPX, NHaml and Spark etc. Most of the developers are familiar with Web Forms View
Engine (ASPX) and Razor View Engine.

 Web Form View Engine was with ASP.NET MVC since beginning.

 Razor View Engine was introduced later in MVC3.

 NHaml is an open source view engine since 2007.

 Spark is also an open source since 2008.

What is the difference between Razor View Engine and ASPX View Engine?

I have written a separate detailed blog post to understand the Difference between ASPX View Engine
and Razor View Engine. You can follow the link to get detailed step by step description here. Most
important differences are listed below:

ASPX View Engine Razor View Engine

WebForms View Engine uses namespace “System.Web.Mvc.WebFormViewEngine”.


“System.Web.Razor” is the namespace for Razor View Engine.

Comparatively fast. A little bit slower than ASPX View Engine.

Nothing like Test Driven Development Good support for Test Driven Development.

Syntax for ASPX View Engine is inherited from Web Forms pages as:

<%= employee.FullName %> Syntax for Razor View Engine is

comparatively less and clean.

@employee.FullName

What is a ViewModel in ASP.NET MVC?


A ViewModel basically acts as a single model object for multiple domain models, facilitating to have
only one optimized object for View to render. Below diagram clearly express the idea of ViewModel in
ASP.NET MVC

There are multiple scenarios where using ViewModel becomes obvious choice. For example:

 Parent-Child View Scenario

 Reports where often aggregated data required

 Model object having lookup data

 Dashboards displaying data from multiple sources

What are ASP.NET MVC HtmlHelpers?

ASP.NET MVC HtmlHelpers fulfills almost the same purpose as that of ASP.NET Web From Controls.
For imlementation point of view, HtmlHelper basically is a method that returns a string ( i.e. an HTML
string to render HTML tags). So, in ASP.NET MVC we have HtmlHelpers for links, Images and for Html
form elements etc. as follows:

@Html.ActionLink(“WebDev Consulting Company Profile”, “CompanyInfo”) will render:

<a href=”/Site/CompanyInfo”>WebDev Consulting Company Profile</a>

and

@Html.TextBox(“strEmployeeName”) renders:

<input id=”strEmployeeName” name=”strEmployeeName” type=”text” value=”” />

Note: Html Helpers are comparatively lightweight because these don’t have ViewState and event model
as for ASP.NET Web Form Controls.

We can also create our Custom Html Helpers to fulfill specific application requirements. There are 2
ways to create custom HtmlHelpers as follows.

What is Bootstrap in MVC5?

Bootstrap (a front-end framework) is an open source collection of tools that contains HTML and CSS-
based design templates along with Javascript to create a responsive design for web applications. Bootstrap
provides a base collection including layouts, base CSS, JavaScript widgets, customizable components and
plugins.

Project Template in ASP.NET MVC5 is now using bootstrap that enhances look and feel with easy
customization. Bootstrap version 3 is added to ASP.NET MVC5 template as shown below. :
Kindly explain Attribute Routing in ASP.NET MVC5?

We already have discussed about Routing in Question#6 that in ASP.NET MVC, we use friendly URLs
that are mapped to controller’s actions instead of physical files as in case of ASP.NET WebForms. Now
in ASP.NET MVC5, we can use attributes to define routes giving better control over the URIs.

We can easily define routes with Controller’s action methods as follows:

Note: Remember that conventional routing approach is not discarded, it’s still there and fully functional.
Also, we can use both routing techniques in a same application. Click here for more details on Attribute
Routing.

What is Scaffolding in ASP.NET MVC? and what are the advantages of using it?

We (developers) spent most of our time writing code for CRUD operations that is connecting to a
database and performing operations like Create, Retrieve, Update and Delete. Microsoft introduces a very
powerful feature called Scaffolding that does the job of writing CRUD operations code for us.

Scaffolding is basically a Code Generation framework. Scaffolding Engine generates basic controllers as
well as views for the models using Micrsoft’s T4 template. Scaffolding blends with Entity Framework
and creates the instance for the mapped entity model and generates code of all CRUD Operations. As a
result we get the basic structure for a tedious and repeatative task.

You can find a detailed Web Development Tutorial with implementation on ASP.NET MVC Scaffolding
here.

Following are the few advantages of Scaffolding:

 RAD approach for data-driven web applications.

 Minimal effort to improve the Views.

 Data Validation based on database schema.

 Easily created filters for foreign key or boolean fields.

Briefly explain ASP.NET Identity?

Microsoft introduces ASP.NET Identity as a system to manage access in ASP.NET application on


premises and also in the cloud. There were issues with Membership Provider Model especially when we
want to implement more advanced security features in our applications, so ASP.NET Identity gets away
from the membership provider model.
If we look into the history of membership, its like follows:

 ASP.NET 2.0 Membership (VS 2005)

 Forms Authentication

 Sql Server Based Membership

 ASP.NET Simple Membership (VS 2010)

 Easy to customize profile

 ASP.NET Web Pages

 ASP.NET Universal Providers (VS2012)

 Support Sql Azure

ASP.NET Identity is much improved system to manage access to our application and services.

1) What is MVC?

MVC is a pattern which is used to split the application's implementation logic into three components:
models, views, and controllers.

2) Can you explain Model, Controller and View in MVC?

• Model – It’s a business entity and it is used to represent the application data.

• Controller – Request sent by the user always scatters through controller and it’s responsibility is
to redirect to the specific view using View() method.

• View – It’s the presentation layer of MVC.

3) Explain the new features added in version 4 of MVC (MVC4)?

Following are features added newly –

• Mobile templates

• Added ASP.NET Web API template for creating REST based services.

• Asynchronous controller task support.

• Bundling the java scripts.

• Segregating the configs for MVC routing, Web API, Bundle etc.

4) Can you explain the page life cycle of MVC?


Below are the processed followed in the sequence -

• App initialization

• Routing

• Instantiate and execute controller

• Locate and invoke controller action

• Instantiate and render view.

5) What are the advantages of MVC over ASP.NET?

• Provides a clean separation of concerns among UI (Presentation layer), model (Transfer


objects/Domain Objects/Entities) and Business Logic (Controller).

• Easy to UNIT Test.

• Improved reusability of model and views. We can have multiple views which can point to the
same model and vice versa.

• Improved structuring of the code.

6) What is Separation of Concerns in ASP.NET MVC?

It’s is the process of breaking the program into various distinct features which overlaps in functionality as
little as possible. MVC pattern concerns on separating the content from presentation and data-processing
from content.

7) What is Razor View Engine?

Razor is the first major update to render HTML in MVC 3. Razor was designed specifically for view
engine syntax. Main focus of this would be to simplify and code-focused templating for HTML
generation. Below is the sample of using Razor:

@model MvcMusicStore.Models.Customer

@{ViewBag.Title = "Get Customers";}

<div class="cust"> <h3><em>@Model.CustomerName</em> </h3>

8) What is the meaning of Unobtrusive JavaScript?

This is a general term that conveys a general philosophy, similar to the term REST (Representational
State Transfer). Unobtrusive JavaScript doesn't intermix JavaScript code in your page markup.
Eg : Instead of using events like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by
their ID or class based on the HTML5 data- attributes.

9) What is the use of ViewModel in MVC?

ViewModel is a plain class with properties, which is used to bind it to strongly typed view. ViewModel
can have the validation rules defined for its properties using data annotations.

10) What you mean by Routing in MVC?

Routing is a pattern matching mechanism of incoming requests to the URL patterns which are registered
in route table. Class – “UrlRoutingModule” is used for the same process.

11) What are Actions in MVC?

Actions are the methods in Controller class which is responsible for returning the view or json data.
Action will mainly have return type – “ActionResult” and it will be invoked from method –
“InvokeAction()” called by controller.

12) What is Attribute Routing in MVC?

ASP.NET Web API supports this type routing. This is introduced in MVC5. In this type of routing,
attributes are being used to define the routes. This type of routing gives more control over classic URI
Routing. Attribute Routing can be defined at controller level or at Action level like –

[Route(“{action = TestCategoryList}”)] - Controller Level

[Route(“customers/{TestCategoryId:int:min(10)}”)] - Action Level

13) How to enable Attribute Routing?

Just add the method – “MapMvcAttributeRoutes()” to enable attribute routing as shown below

public static void RegistearRoutes(RouteCollection routes)

routes.IgnoareRoute("{resource}.axd/{*pathInfo}");

//enabling attribute routing

routes.MapMvcAttributeRoutes();

//convention-based routing

routes.MapRoute

name: "Default",
url: "{controller}/{action}/{id}",

defaults: new { controller = "Customer", action = "GetCustomerList", id = UrlParameter.Optional }

);

14) Explain JSON Binding?

JavaScript Object Notation (JSON) binding support started from MVC3 onwards via the
newJsonValueProviderFactory, which allows the action methods to accept and model-bind data in JSON
format. This is useful in Ajax scenarios like client templates and data binding that need to post data back
to the server.

15) Explain Dependency Resolution?

Dependency Resolver again has been introduced in MVC3 and it is greatly simplified the use of
dependency injection in your applications. This turn to be easier and useful for decoupling the application
components and making them easier to test and more configurable.

16) Explain Bundle.Config in MVC4?

"BundleConfig.cs" in MVC4 is used to register the bundles by the bundling and minification system.
Many bundles are added by default including jQuery libraries like - jquery.validate, Modernizr, and
default CSS references.

17) How route table has been created in ASP.NET MVC?

Method – “RegisterRoutes()” is used for registering the routes which will be added in
“Application_Start()” method of global.asax file, which is fired when the application is loaded or started.

18) Which are the important namespaces used in MVC?

Below are the important namespaces used in MVC -

System.Web.Mvc

System.Web.Mvc.Ajax

System.Web.Mvc.Html

System.Web.Mvc.Async

19) What is ViewData?


Viewdata contains the key, value pairs as dictionary and this is derived from class –
“ViewDataDictionary“. In action method we are setting the value for viewdata and in view the value will
be fetched by typecasting.

20) What is the difference between ViewBag and ViewData in MVC?

ViewBag is a wrapper around ViewData, which allows to create dynamic properties. Advantage of
viewbag over viewdata will be –

• In ViewBag no need to typecast the objects as in ViewData.

• ViewBag will take advantage of dynamic keyword which is introduced in version 4.0. But before
using ViewBag we have to keep in mind that ViewBag is slower than ViewData.

21) Explain TempData in MVC?

TempData is again a key, value pair as ViewData. This is derived from “TempDataDictionary” class.
TempData is used when the data is to be used in two consecutive requests, this could be between the
actions or between the controllers. This requires typecasting in view.

22) What are HTML Helpers in MVC?

• HTML Helpers are like controls in traditional web forms. But HTML helpers are more
lightweight compared to web controls as it does not hold viewstate and events.

• HTML Helpers returns the HTML string which can be directly rendered to HTML page. Custom
HTML Helpers also can be created by overriding “HtmlHelper” class.

23) What are AJAX Helpers in MVC?

AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which
performs the request asynchronously and these are extension methods of AJAXHelper class which exists
in namespace - System.Web.Mvc.

24) What are the options can be configured in AJAX helpers?

Below are the options in AJAX helpers –

• Url – This is the request URL.

• Confirm – This is used to specify the message which is to be displayed in confirm box.

• OnBegin – Javascript method name to be given here and this will be called before the AJAX
request.
• OnComplete – Javascript method name to be given here and this will be called at the end of
AJAX request.

• OnSuccess - Javascript method name to be given here and this will be called when AJAX request
is successful.

• OnFailure - Javascript method name to be given here and this will be called when AJAX request
is failed.

• UpdateTargetId – Target element which is populated from the action returning HTML.

25) What is Layout in MVC?

Layout pages are similar to master pages in traditional web forms. This is used to set the common look
across multiple pages. In each child page we can find – /p>

@{

Layout = "~/Views/Shared/TestLayout1.cshtml";

This indicates child page uses TestLayout page as it’s master page.

26) Explain Sections is MVC?

Section are the part of HTML which is to be rendered in layout page. In Layout page we will use the
below syntax for rendering the HTML –

@RenderSection("TestSection")

And in child pages we are defining these sections as shown below –

@section TestSection{

<h1>Test Content</h1>

If any child page does not have this section defined then error will be thrown so to avoid that we can
render the HTML like this –

@RenderSection("TestSection", required: false)

27) Can you explain RenderBody and RenderPage in MVC?

RenderBody is like ContentPlaceHolder in web forms. This will exist in layout page and it will render the
child pages/views. Layout page will have only one RenderBody() method. RenderPage also exists in
Layout page and multiple RenderPage() can be there in Layout page.

28) What is ViewStart Page in MVC?


This page is used to make sure common layout page will be used for multiple views. Code written in this
file will be executed first when application is being loaded.

29) Explain the methods used to render the views in MVC?

Below are the methods used to render the views from action -

• View() – To return the view from action.

• PartialView() – To return the partial view from action.

• RedirectToAction() – To Redirect to different action which can be in same controller or in


different controller.

• Redirect() – Similar to “Response.Redirect()” in webforms, used to redirect to specified URL.

• RedirectToRoute() – Redirect to action from the specified URL but URL in the route table has
been matched.

30) What are the sub types of ActionResult?

ActionResult is used to represent the action method result. Below are the subtypes of ActionResult –

• ViewResult

• PartialViewResult

• RedirectToRouteResult

• RedirectResult

• JavascriptResult

• JSONResult

• FileResult

• HTTPStatusCodeResult

31) What are Non Action methods in MVC?

In MVC all public methods have been treated as Actions. So if you are creating a method and if you do
not want to use it as an action method then the method has to be decorated with “NonAction” attribute as
shown below –

[NonAction]

public void TestMethod()

{
// Method logic

32) How to change the action name in MVC?

“ActionName” attribute can be used for changing the action name. Below is the sample code snippet to
demonstrate more –

[ActionName("TestActionNew")]

public ActionResult TestAction()

return View();

So in the above code snippet “TestAction” is the original action name and in “ActionName” attribute,
name - “TestActionNew” is given. So the caller of this action method will use the name
“TestActionNew” to call this action.

33) What are Code Blocks in Views?

Unlike code expressions that are evaluated and sent to the response, it is the blocks of code that are
executed. This is useful for declaring variables which we may be required to be used later.

@{

int x = 123;

string y = "aa";

34) What is the "HelperPage.IsAjax" Property?

The HelperPage.IsAjax property gets a value that indicates whether Ajax is being used during the request
of the Web page.

35) How we can call a JavaScript function on the change of a Dropdown List in MVC?

Create a JavaScript method:

<script type="text/javascript">

function DrpIndexChanged() { }

</script>
Invoke the method:

<%:Html.DropDownListFor(x => x.SelectedProduct, new SelectList(Model.Customers, "Value", "Text"),


"Please Select a Customer", new { id = "ddlCustomers", onchange=" DrpIndexChanged ()" })%>

36) What are Validation Annotations?

Data annotations are attributes which can be found in the "System.ComponentModel.DataAnnotations"


namespace. These attributes will be used for server-side validation and client-side validation is also
supported. Four attributes - Required, String Length, Regular Expression and Range are used to cover the
common validation scenarios.

37) Why to use Html.Partial in MVC?

This method is used to render the specified partial view as an HTML string. This method does not depend
on any action methods. We can use this like below –

@Html.Partial("TestPartialView")

38) What is Html.RenderPartial?

Result of the method – “RenderPartial” is directly written to the HTML response. This method does not
return anything (void). This method also does not depend on action methods. RenderPartial() method
calls “Write()” internally and we have to make sure that “RenderPartial” method is enclosed in the
bracket. Below is the sample code snippet –

@{Html.RenderPartial("TestPartialView"); }

39) What is RouteConfig.cs in MVC 4?

"RouteConfig.cs" holds the routing configuration for MVC. RouteConfig will be initialized on
Application_Start event registered in Global.asax.

40) What are Scaffold templates in MVC?

Scaffolding in ASP.NET MVC is used to generate the Controllers,Model and Views for create, read,
update, and delete (CRUD) functionality in an application. The scaffolding will be knowing the naming
conventions used for models and controllers and views.

41) Explain the types of Scaffoldings.

Below are the types of scaffoldings –

• Empty

• Create

• Delete

• Details
• Edit

• List

42) Can a view be shared across multiple controllers? If Yes, How we can do that?

Yes, we can share a view across multiple controllers. We can put the view in the “Shared” folder. When
we create a new MVC Project we can see the Layout page will be added in the shared folder, which is
because it is used by multiple child pages.

43) What are the components required to create a route in MVC?

• Name - This is the name of the route.

• URL Pattern – Placeholders will be given to match the request URL pattern.

• Defaults –When loading the application which controller, action to be loaded along with the
parameter.

44) Why to use “{resource}.axd/{*pathInfo}” in routing in MVC?

Using this default route - {resource}.axd/{*pathInfo}, we can prevent the requests for the web resources
files like - WebResource.axd or ScriptResource.axd from passing to a controller.

45) Can we add constraints to the route? If yes, explain how we can do it?

Yes we can add constraints to route in following ways –

• Using Regular Expressions

• Using object which implements interface - IRouteConstraint.

46) What are the possible Razor view extensions?

Below are the two types of extensions razor view can have –

• .cshtml – In C# programming language this extension will be used.

• .vbhtml - In VB programming language this extension will be used.

47) What is PartialView in MVC?

PartialView is similar to UserControls in traditional web forms. For re-usability purpose partial views are
used. Since it’s been shared with multiple views these are kept in shared folder. Partial Views can be
rendered in following ways –

• Html.Partial()

• Html.RenderPartial()

48) How we can add the CSS in MVC?


Below is the sample code snippet to add css to razor views –

<link rel="StyleSheet" href="/@Href(~Content/Site.css")" type="text/css"/>

49) Can I add MVC Testcases in Visual Studio Express?

No. We cannot add the test cases in Visual Studio Express edition it can be added only in Professional
and Ultimate versions of Visual Studio.

50) What is the use .Glimpse in MVC?

Glimpse is an open source tool for debugging the routes in MVC. It is the client side debugger. Glimpse
has to be turned on by visiting to local url link -

• http://localhost:portname//glimpse.axd

This is a popular and useful tool for debugging which tracks the speed details, url details etc.

51) What is the need of Action Filters in MVC?

Action Filters allow us to execute the code before or after action has been executed. This can be done by
decorating the action methods of controls with MVC attributes.

52) Mention some action filters which are used regularly in MVC?

Below are some action filters used –

• Authentication

• Authorization

• HandleError

• OutputCache

53) How can we determine action invoked from HTTP GET or HTTP POST?

This can be done in following way –

• Use class – “HttpRequestBase” and use the method – “HttpMethod” to determine the action
request type.

54) In Server how to check whether model has error or not in MVC?

Whenever validation fails it will be tracked in ModelState. By using property – IsValid it can be
determined. In Server code, check like this –

if(ModelState.IsValid){

// No Validation Errors
}

55) How to make sure Client Validation is enabled in MVC?

In Web.Config there are tags called – “ClientValidationEnabled” and “UnobtrusiveJavaScriptEnabled”.


We can set the client side validation just by setting these two tags “true”, then this setting will be applied
at the application level.

<add key="ClientValidationEnabled" value="true" />

<add key="UnobtrusiveJavaScriptEnabled" value="true" />

56) What are Model Binders in MVC?

For Model Binding we will use class called – “ModelBinders”, which gives access to all the model
binders in an application. We can create a custom model binders by inheriting “IModelBinder”.

57) How we can handle the exception at controller level in MVC?

Exception Handling is made simple in MVC and it can be done by just overriding “OnException” and set
the result property of the filtercontext object (as shown below) to the view detail, which is to be returned
in case of exception.

protected overrides void OnException(ExceptionContext filterContext)

58) Does Tempdata hold the data for other request in MVC?

If Tempdata is assigned in the current request then it will be available for the current request and the
subsequent request and it depends whether data in TempData read or not. If data in Tempdata is read then
it would not be available for the subsequent requests.

59) Explain Keep method in Tempdata in MVC?

As explained above in case data in Tempdata has been read in current request only then “Keep” method
has been used to make it available for the subsequent request.

@TempData[“TestData”];

TempData.Keep(“TestData”);

60) Explain Peek method in Tempdata in MVC?

Similar to Keep method we have one more method called “Peek” which is used for the same purpose.
This method used to read data in Tempdata and it maintains the data for subsequent request.

string A4str = TempData.Peek("TT").ToString();


61) What is Area in MVC?

Area is used to store the details of the modules of our project. This is really helpful for big applications,
where controllers, views and models are all in main controller, view and model folders and it is very
difficult to manage.

62) How we can register the Area in MVC?

When we have created an area make sure this will be registered in “Application_Start” event
inGlobal.asax. Below is the code snippet where area registration is done –

protected void Application_Start()

AreaRegistration.RegisterAllAreas();

63) What are child actions in MVC?

To create reusable widgets child actions are used and this will be embedded into the parent views. In
MVC Partial views are used to have reusability in the application. Child action mainly returns the partial
views.

64) How we can invoke child actions in MVC?

“ChildActionOnly” attribute is decorated over action methods to indicate that action method is a child
action. Below is the code snippet used to denote the child action –

[ChildActionOnly]

public ActionResult MenuBar()

//Logic here

return PartialView();

65) What is Dependency Injection in MVC?

It’s a design pattern and is used for developing loosely couple code. This is greatly used in the software
projects. This will reduce the coding in case of changes on project design so this is vastly used.

66) Explain the advantages of Dependency Injection (DI) in MVC?

Below are the advantages of DI –


• Reduces class coupling

• Increases code reusing

• Improves code maintainability

• Improves application testing

67) Explain Test Driven Development (TDD) ?

TDD is a methodology which says, write your tests first before you write your code. In TDD, tests drive
your application design and development cycles. You do not do the check-in of your code into source
control until all of your unit tests pass.

68) Explain the tools used for unit testing in MVC?

Below are the tools used for unit testing –

• NUnit

• xUnit.NET

• Ninject 2

• Moq

69) What is Representational State Transfer (REST) mean?

REST is an architectural style which uses HTTP protocol methods like GET, POST, PUT, and DELETE
to access the data. MVC works in this style. In MVC 4 there is a support for Web API which uses to build
the service using HTTP verbs.

70) How to use Jquery Plugins in MVC validation?

We can use dataannotations for validation in MVC. If we want to use validation during runtime using
Jquery then we can use Jquery plugins for validation.

Eg: If validation is to be done on customer name textbox then we can do as –

$('#CustomerName').rules("add", {

required: true,

minlength: 2,

messages: {

required: "Please enter name",

minlength: "Minimum length is 2"


}

});

71) How we can multiple submit buttons in MVC?

Below is the scenario and the solution to solve multiple submit buttons issue.

Scenario –

@using (Html.BeginForm(“MyTestAction”,”MyTestController”)

<input type="submit" value="MySave" />

<input type="submit" value="MyEdit" />

Solution :

Public ActionResult MyTestAction(string submit) //submit will have value either “MySave” or “MyEdit”

// Write code here

72) What are the differences between Partial View and Display Template and Edit Templates in MVC?

• Display Templates – These are model centric. Meaning it depends on the properties of the view
model used. It uses convention that will only display like divs or labels.

• Edit Templates – These are also model centric but will have editable controls like Textboxes.

• Partial View – These are view centric. These will differ from templates by the way they render
the properties (Id’s) Eg : CategoryViewModel has Product class property then it will be rendered as
Model.Product.ProductName but in case of templates if we CategoryViewModel has List<Product> then
@Html.DisplayFor(m => m.Products) works and it renders the template for each item of this list.

73) Can I set the unlimited length for “maxJsonLength” property in config?

No. We can’t set unlimited length for property maxJsonLength. Default value is - 102400 and maximum
value what we can set would be – 2147483644.

74) Can I use Razor code in Javascript in MVC?


Yes. We can use the razor code in javascript in cshtml by using <text> element.

<script type="text/javascript">

@foreach (var item in Model) {

<text>

//javascript goes here which uses the server values

</text>

</script>

75) How can I return string result from Action in MVC?

Below is the code snippet to return string from action method –

public ActionResult TestAction() {

return Content("Hello Test !!");

76) How to return the JSON from action method in MVC?

Below is the code snippet to return string from action method –

public ActionResult TestAction() {

return JSON(new { prop1 = “Test1”, prop2 = “Test2” });

77) How we can override the action names in MVC?

If we want to override the action names we can do like this –

[ActionName("NewActionName")]

public ActionResult TestAction() {

return View();

1. Which is the best approach to assign a session in MVC?

A) System.Web.HttpContext.Current.Session["LoginID"] =7;
B) Current.Session["LoginID"] =7;

C) Session["LoginID"] =7;

D) None

2. RedirectToActionPermanent() Method for which Status code represents?

A) 304

B) 302

C) 301

D) 300

E) None

3. RedirectToAction() Method for which Status code represents?

A) 304

B) 302

C) 301

D) 300

E) None

4. What is ActionResult() ?

A) It is an abstract Class

B) It is a Concrete Class

C) Both A and B

D) None

5. What is ViewResult() ?

A) It is an abstract Class

B) It is a Concrete Class

C) Both A and B

D) None
6. return View() works like in ASP.Net MVC C# as

A) Server.Transfer()

B) Response.Redirect()

C) Both A and B

D) None

7. RedirectToAction() works like in ASP.Net MVC C# as

A) Server.Transfer()

B) Response.Redirect()

C) Both A and B

D) None

8. In which format data can be return from XML into table ?

A) DataSet

B) Datatable

C) A and B

D) None

9. Can we use view state in MVC ?

A) Yes

B) No

C) Both A & B

D) None

10. What Request Processing technique follows ASP.Net ?

A) Top-Down

B) Down-Up

C) Pipeline
D) Water fall

11. What is DRY principle in ASP.Net ?

A) Don't repeat yourself.

B) Don't revise yourself.

C) both a and b

D) None

12. What is default authentication in Internet Information Services (IIS)?

A) Standard User

B) Administrator

C) Anonymous

D) None

13. What is the extension of MVC view when using C#?

A) cshtml

B) vbhtml

C) None

D) Both A & B

14. What is the extension of MVC view when using vb.net?

A) cshtml

B) vbhtml

C) None

D) Both A & B

15. How can you comment using Razor Syntax?

A) *@ Comment me *@

B) @* Comment me *@

C) @* Comment me @*

D) *@ Comment me @*
E) None

16. Which Namespace is used for Razor View Engine ?

A) System.Web.Razor

B) System.Web.Mvc.WebFormViewEngine

C) Both A & B

D) None

17. Which Namespace is used for ASPX View Engine ?

A) System.Web.Razor

B) System.Web.Mvc.WebFormViewEngine

C) Both A & B

D) None

18. The Razor View Engine uses to render server side content.

A) @

B) <%= %>

C) Both A & B

D) None

19. The ASPX View Engine uses to render server side content.

A) @

B) <%= %>

C) Both A & B

D) None

20. Which is more faster between ASPX View Engine and Razor View Engine.

A) ASPX View Engine

B) Razor View Engine

C) Both A & B
D) None

21. Does Razor Engine supports for TDD ?

A) Yes

B) No

C) None

22. Does ASPX View Engine supports for TDD ?

A) Yes

B) No

C) None

22. How to Print value from Controller to View in MVC ?

A) ViewBag.ECMDetail = "my message"; and in view @ViewBag.ECMDetail

B) ViewBag.ECMDetail = "my message"; and in view ViewBag.ECMDetail

B) ViewBag.ECMDetail = "my message"; and in view ViewBag.Title

D) None

23. If you have already implemented different filters then what will be order of these filters?

1) Authorization filters

2) Action filters

3) Response filters

4) Exception filters

24. Can you specify different types of filters in ASP.Net MVC application?

1) Authorization filters (IAuthorizationFilter)

2) Action filters (IActionFilter)

3) Result filters (IResultFilter)

4) Exception filters (IExceptionFilter)


25. What are the advantages of using ASP.NET routing?

Answer: Clean URLs is originally brought from Ruby on Rails. http://www.technologycrowds.com?


abc=10 , now clean URL in MVC ASP.Net will be work like http://www.technologycrowds.com/abc/10

26. What is the significance of ASP.NET routing?

Answer: Default Route Name:

"{controller}/{action}/{id}", // URL with parameters

By default routing is defined under Global.asax file. MVC ASP.Net uses routing to map between
incoming browser request to controller action methods.

27. Can be it possible to share single view across multiple controllers in MVC?

Answer: We can put the view under shared folder, it will automatically view the across the multiple
controllers.

28. Are MVC and Web API merged into one in MVC 6?

A) Yes

B) No

C) Both A & B

D) None

29. Does MVC 6 introduced new JSON project based structure?

A) Yes

B) No

C) Both A & B

D) None

30. Does MVC 6 allow only save change, hitting the save but then refreshing the browser to reflect
changes?
A) Yes

B) No

C) Both A & B

D) None

31. Does vNext is now Open Sourced via the .NET Foundation and open to public contributions.

A) Yes

B) No

C) Both A & B

D) None

32. Can vNext runs on both Mac and Linux today (Mono Version)?

A) Yes

B) No

C) Both A & B

D) None

33. What is the difference between MVC (Model View Controller) and MVP (Model View Presenter)?

Answer: MVC controller handles all the requests, MVP handles as the handler and also handles the all
requests as well.

34. How does work Viewstart in MVC (ASP.Net)?

A) Viestart is used to layout of the application.

B) Viewstart is used like Masterpage in traditional forms (ASP.Net pages).

C) Viewstart render first in the views.

D) A, B and C.

E) None
Viewstart Code Snippet

@{

Layout = "~/Views/Shared/_Layout.cshtml";

35. Viewstart comes under which folder name ?

A) Views

B) Account

C) Shared

D) Home

36. Does Viewstart override all Views layout/template under "Views" folder in MVC ?

A) Yes

B) No

C) Both A & B

D) None

37. What is the name of default Viewstart Page in ASP.Net MVC ?

A) _ViewStart.cshtml

B) _Layout.cshtml

C) _Login.cshtml

D) None
38. Can we use third party View Engine using ASP.Net MVC Engine ?

Yes, below are the top five alternative ASP.Net MVC View Engines.

1. Spark (Castle MonoRail framework projects), Open Sourced, it is popular as MVCContrib


library.

2. NHaml works like inline page templating.

3. NDjango uses F# Language.

4. Hasic uses VB.Net, XML.

5. Bellevue for ASP.NEt view, It respects HTML class first.

39. What is scaffolding using ASP.Net MVC Engine?

Answer: Scaffolding helps us to write CRUD operations blend using Entity Framework, It helps
developer to write down simply even yet complex business logic.

40. What is life cycle in ASP.Net MVC Engine?

Step 1: Fill Route (Global.asax file will hit first).

Step 2: Fetch Route: It will gether information about controller and action to invoke.

Step 3: Request context

Step 4: Controller instance: it calls Controller class and method.

Step 5: Executing Action: It determines which action to be executed

Step 6: Result (View): Now Action method executed and returns back response to view in differentiating
forms like Json, View Result, File Result etc.

41. Which is the way to render Partial View using ASP.Net MVC Razor Engine?

A) @Html.Partial("_PartialHeader")

B) @Html.PartialView("_PartialHeader")

C) @Html.PartialHtml("_PartialHeader")

D) B and C
E) None

42. Which Namespace is used to "Display" in Data Annotation using MVC ?

A) System.ComponentModel

B) System.ComponentModel.DataAnnotations

C) Both A and B

D) None

43. Which Namespaces are required to Data Annotation using MVC ?

A) System.ComponentModel

B) System.ComponentModel.DataAnnotations

C) Both A and B

D) None

44. Are both TempData/ViewData require typecasting in MVC?

A) Both (TempData/ViewData) requires type casting to avoid null exception.

B) No, these (TempData/ViewData) does not require type casting.

C) Both A) & B)

D) None

45. Is ViewBag slower than ViewData in MVC?

A) Yes

B) No

C) Both A) & B)

D) None

46. Is ViewData faster than ViewBag in MVC?


A) Yes

B) No

C) Both A) & B)

D) None

47. Are both TempData/ViewData property of Controller base class in MVC?

A) Yes

B) No

C) Both A) & B)

D) None

48. Does TempData used to pass data from one page to another page in MVC?

A) Yes

B) No

C) Both A) & B)

D) None

49. Can ASP.Net Web API specialize to XML or JSON ?

A) Yes

B) No

C) None

50. Does Web API (ASP.Net) supports to non SOAP based like XML or JSON ?

A) Yes

B) No

C) None
51. Does Web API (ASP.Net) supports to both version mobile apps and others ?

A) Yes

B) No

C) Both A & B

D) None

52. Can ASP.Net Web API, it works HTTP standard verbs like POST, GET, PUT, DELETE (CRUD
Operations) ?

A) Yes

B) No

C) Both A & B

D) None

53. Can ASP.Net Web API ability to both self hosting (outside of IIS) and IIS ?

A) Yes

B) No

C) None

54. Can ASP.Net Web API has ability to transport non HTTP protocols like TCP, UDP, Named Pipes
etc ?

A) Yes

B) No

C) None

55. What is AuthConfig.cs in ASP.Net MVC ?

A) AuthConfig.cs is used to configure route settings

B) AuthConfig.cs is used to configure security settings including sites oAuth Login.

C) None

D) All
56. What is BundleConfig.cs in ASP.Net MVC ?

A) BundleConfig.cs in MVC is used to register filters for different purposes.

B) BundleConfig.cs in MVC is used to register bundles used by the bundling and minification, serveral
bundles are added by default like jQuery, jQueryUI, jQuery validation, Modernizr, default CSS
references.

C) All

D) None

57. What is FilterConfig.cs in ASP.Net MVC ?

A) FilterConfig.cs is used to register global MVC filters, HandleErrorAttribute is registered by default


filter. We can also register other filters.

B) FilterConfig.cs is used to register global MVC bundles.

C) None

D) All

58. What is RouteConfig.cs in ASP.Net MVC?

A) RouteConfig.cs is used to register MVC config statements, route config.

B) RouteConfig.css is used to register global MVC bundles.

C) None

D) All

59. What is the difference between HtmlTextbox and HtmlTextboxFor using ASP.Net MVC Razor
Engine?

A) @Html.TextBox is not strongly typed, @Html.TextBoxFor is strongly typed that is why should be use
@Html.TextBoxFor in MVC Razor Engine.

B) @Html.TextBox is strongly typed, @Html.TextBoxFor is not strongly typed that is why should be use
@Html.TextBox in MVC Razor Engine.

C) None

D) Both A and B
Syntax

@Html.Partial("_viewname");

60. What is the benefits of Html.RenderPartial using ASP.Net MVC Razor Engine?

A) @Html.RenderPartial Returns response, moreover requires to create action.

B) @Html.RenderPartial Returns nothing (void), it is faster than @Html.Partial, moreover requires not to
create action.

C) None

D) Both A and B

Syntax

@Html.Partial("_viewname");

@Html.RenderPartial("_viewname");

61. What is the benefits of Html.Partial using ASP.Net MVC Razor Engine?

A) @Html.RenderPartial Returns response, moreover requires to create action.

B) @Html.RenderPartial Returns string value, it is slower than @Html.RenderPartial, moreover requires


not to create action.

C) None

D) Both A and B

Syntax

@Html.Partial("_viewname");

62. How to check Request coming from which controller using MVC ASP.Net?

A) var _controller = HttpContext.Current.Request.RequestContext.Values["Controller"].ToString();

B) var _controller =
HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();

C) var _controller = RouteData.Values["Controller"].ToString();


D) None

63. For which ModelState.IsValid Validate ?

A) It checks for Entityframework Model state.

B) It checks for valid Model State using DataAnnotations.

C) It checks for SQL database state.

D) None

64. Which Name space is used to create chart using ASP.Net MVC?

A) using System.Web.MVC;

B) using System.Web.Helpers;

c) using System.Web.Chart;

D) All

65. How can we provide Height and Width to MVC Charts ?

A) new Chart(width - 600, height - 400)

B) new Chart(width = 600, height = 400)

C) new Chart(width: 600, height: 400)

D) All

66. How can we set theme to MVC Charts?

A) new Chart(width: 600, height: 400, theme: ChartTheme.Vanilla3D)

B) new Chart(width: 600, height: 400, theme: ChartTheme = Vanilla3D)

C) new Chart(width: 600, height: 400, theme: Vanilla3D)

D) None
67. How can we give Title to MVC Charts?

A) var chart = AddTitle("My First Chart")

B) .AddTitle("My First Chart")

C) .AddTitle('My First Chart')

D) All

68. How can we add Series to MVC Charts?

A) .AddSeries(chartType: "Bar", xValue: xValue, yValues: yValue)

B) .AddSeries(chartType: "Bar", xValue = xValue, yValues = yValue)

C) .AddSeries(chartType: "Bar", xValue: xValue, yValues: yValue)

D) None

69. How can we add Chart Type to MVC Charts?

A) .NewSeries(chartType: "Bar")

B) .Series(chartType: "Bar")

C) .AddSeries(chartType: "Bar")

D) All

70. How can we write Chart output to MVC View?

A) .Write(bmp);

B) Write("bmp");

C) .Write("bmp");

D) All
71. How can we Show Chart output to MVC View?

Answer: C)

72. Which name space using can send email in ASP.Net MVC?

A) using System.Net.Mail;

B) using System.Net;

C) using System.Mail;

D) None

MailMessage mail = new MailMessage();

73. If Razor View Engine need to add JQuery function and contain @ special character then how we can
write it in Razor View?

A) Replace @ to @@@ (tripple)

B) Replace @ to @@ (double)

C) None

D) Both (A & B)

74. How to set Default Value to Hidden Input Box using ASP.Net MVC?

A) @Html.HiddenFor(m => m.Name, "Jack")

B) @Html.HiddenFor(m => m.Name, new { Value = "Jack"})

C) @Html.Hidden(m => m.Name, new { Value = "Jack"})

D) None

75. How to check all errors of Model using ASP.Net MVC?

A) var errors = Model.Values.SelectMany(v => v.Errors);

B) var errors = ModelState.SelectMany(v => v.Errors);


C) var errors = ModelState.Values.SelectMany(v => v.Errors);

D) None

76. AuthConfig.cs file is under in which App folder ?

A) App_Data

B) App_Start

C) Content

D) Filters

77. BundleConfig.cs file is under in which App folder ?

A) App_Data

B) App_Start

C) Content

D) Filters

78. FilterConfig.cs file is under in which App folder ?

A) App_Data

B) App_Start

C) Content

D) Filters

79. RouteConfig.cs file is under in which App folder ?

A) App_Data

B) App_Start

C) Content

D) Filters
80. WebApiConfig.cs file is under in which App folder ?

A) App_Data

B) App_Start

C) Content

D) Filters

81. Can you list the main types of result using ASP.Net MVC?

There are total 10 main types of result, ActionResult is main type and others are sub types of results as
listed below:

• System.Web.Mvc.ActionResult

• System.Web.Mvc.ContentResult

• System.Web.Mvc.EmptyResult

• System.Web.Mvc.FileResult

• System.Web.Mvc.HttpStatusCodeResult

• System.Web.Mvc.JavaScriptResult

• System.Web.Mvc.JsonResult

• System.Web.Mvc.RedirectResult

• System.Web.Mvc.RedirectToRouteResult

• System.Web.Mvc.ViewResultBase

82. Which filter will be execute at first using ASP.Net MVC?

A) Action filters

B) Authorization filters

C) Response filters

D) Exception filters

83. Which filter will be execute at last using ASP.Net MVC?


A) Action filters

B) Authorization filters

C) Exception filters

D) Response filters

1) Explain what is Model-View-Controller?

MVC is a software architecture pattern for developing web application. It is handled by three objects
Model-View-Controller.

2) Mention what does Model-View-Controller represent in an MVC application?

In an MVC model,

• Model– It represents the application data domain. In other words applications business logic is
contained within the model and is responsible for maintaining data

• View– It represents the user interface, with which the end users communicates. In short all the
user interface logic is contained within the VIEW

• Controller– It is the controller that answers to user actions. Based on the user actions, the
respective controller responds within the model and choose a view to render that display the user
interface. The user input logic is contained with-in the controller

3) Explain in which assembly is the MVC framework is defined?

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

4) List out few different return types of a controller action method?

• View Result

• Javascript Result

• Redirect Result

• Json Result

• Content Result

5) Mention what is the difference between adding routes, to a webform application and an MVC
application?
To add routes to a webform application, we can use MapPageRoute() method of the RouteCollection
class, where adding routes to an MVC application, you can use MapRoute() method.

6) Mention what are the two ways to add constraints to a route?

The two methods to add constraints to a route is

• Use regular expressions

• Use an object that implements IRouteConstraint Interface

7) Mention what is the advantages of MVC?

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

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

• MVC makes your project more systematic

8) Mention what “beforFilter()”,“beforeRender” and “afterFilter” functions do in Controller?

• beforeFilter(): This function is run before every action in the controller. It’s the right place to
check for an active session or inspect user permissions.

• beforeRender(): This function is called after controller action logic, but before the view is
rendered. This function is not often used, but may be required If you are calling render() manually before
the end of a given action

• afterFilter(): This function is called after every controller action, and after rendering is done. It is
the last controller method to run

9) Explain the role of components Presentation, Abstraction and Control in MVC?

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

• Abstraction: It is the business domain functionality within the application

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

10) Mention the advantages and disadvantages of MVC model?

Advantages Disadvantages

• It represents clear separation between business logic and presentation logic

• Each MVC object has different responsibilities


• The development progresses in parallel

• Easy to manage and maintain

• All classes and object are independent of each other • The model pattern is little
complex

• Inefficiency of data access in view

• With modern user interface, it is difficult to use MVC

• You need multiple programmers for parallel development

• Multiple technologies knowledge is required

11) Explain the role of “ActionFilters” in MVC?

In MVC “ ActionFilters” help you to execute logic while MVC action is executed or its executing.

12) Explain what are the steps for the execution of an MVC project?

The steps for the execution of an MVC project includes

• Receive first request for the application

• Performs routing

• Creates MVC request handler

• Create Controller

• Execute Controller

• Invoke action

• Execute Result

13) Explain what is routing? What are the three segments for routing is important?

Routing helps you to decide a URL structure and map the URL with the Controller.

The three segments that are important for routing is

• ControllerName

• ActionMethodName

• Parameter

14) Explain how routing is done in MVC pattern?


There is a group of routes called the RouteCollection, which consists of registered routes in the
application. The RegisterRoutes method records the routes in this collection. A route defines a URL
pattern and a handler to use if the request matches the pattern. The first parameter to the MapRoute
method is the name of the route. The second parameter will be the pattern to which the URL matches.
The third parameter might be the default values for the placeholders if they are not determined.

15) Explain using hyperlink how you can navigate from one view to other view?

By using “ActionLink” method as shown in the below code. The below code will make a simple URL
which help to navigate to the “Home” controller and invoke the “GotoHome” action.

Collapse / Copy Code

<%= Html.ActionLink(“Home”, “Gotohome”) %>

16) Mention how can maintain session in MVC?

Session can be maintained in MVC by three ways tempdata, viewdata, and viewbag.

17) Mention what is the difference between Temp data, View, and View Bag?

• Temp data: It helps to maintain data when you shift from one controller to other controller.

• View data: It helps to maintain data when you move from controller to view

• View Bag: It’s a dynamic wrapper around view data

18) What is partial view in MVC?

Partial view in MVC renders a portion of view content. It is helpful in reducing code duplication. In
simple terms, partial view allows to render a view within the parent view.

19) Explain how you can implement Ajax in MVC?

In Ajax, MVC can be implemented in two ways

• Ajax libraries

• Jquery

20) Mention what is the difference between “ActionResult” and “ViewResult” ?

“ActionResult” is an abstract class while “ViewResult” is derived from “AbstractResult” class.


“ActionResult” has a number of derived classes like “JsonResult”, “FileStreamResult” and
“ViewResult” .

“ActionResult” is best if you are deriving different types of view dynamically.


21) Explain how you can send the result back in JSON format in MVC?

In order to send the result back in JSON format in MVC, you can use “JSONRESULT” class.

22) Explain what is the difference between View and Partial View?

View Partial View

• It contains the layout page

• Before any view is rendered, viewstart page is rendered

• View might have markup tags like body, html, head, title, meta etc.

• View is not lightweight as compare to Partial View • It does not contain the layout
page

• Partial view does not verify for a viewstart.cshtml. We cannot put common code for a partial
view within the viewStart.cshtml.page

• Partial view is designed specially to render within the view and just because of that it does not
consist any mark up

• We can pass a regular view to the RenderPartial method

23) List out the types of result in MVC?

In MVC, there are twelve types of results in MVC where “ActionResult” class is the main class while the
11 are their sub-types

• ViewResult

• PartialViewResult

• EmptyResult

• RedirectResult

• RedirectToRouteResult

• JsonResult

• JavaScriptResult

• ContentResult

• FileContentResult

• FileStreamResult
• FilePathResult

24) Mention what is the importance of NonActionAttribute?

All public methods of a controller class are treated as the action method if you want to prevent this default
method then you have to assign the public method with NonActionAttribute.

25) Mention what is the use of the default route {resource}.axd/{*pathinfo} ?

This default route prevents request for a web resource file such as Webresource.axd or
ScriptResource.axd from being passed to the controller.

26) Mention the order of the filters that get executed, if the multiple filters are implemented?

The filter order would be like

• Authorization filters

• Action filters

• Response filters

• Exception filters

27) Mention what filters are executed in the end?

In the end “Exception Filters” are executed.

28) Mention what are the file extensions for razor views?

For razor views the file extensions are

• .cshtml: If C# is the programming language

• .vbhtml: If VB is the programming language

29) Mention what are the two ways for adding constraints to a route?

Two methods for adding constraints to route is

• Using regular expressions

• Using an object that implements IRouteConstraint interface

30) Mention two instances where routing is not implemented or required?

Two instance where routing is not required are

• When a physical file is found that matches the URL pattern

• When routing is disabled for a URL pattern


31) Mention what are main benefits of using MVC?

There are two key benefits of using MVC

• As the code is moved behind a separate class file, you can use the code to a great extent

• As behind code is simply moved to.NET class, it is possible to automate UI testing. This gives an
opportunity to automate manual testing and write unit tests.

1. What is main objective of ASP.NET MVC 4 or What is new in MVC4 ?

Ans.

 Easy Mobile web applications (ASP.NET MVC 4 complete focus on Mobile application
development)

 Full HTML5 support

 ASP.NET MVC web application with cloud support

 Working with different mobile and desktop web browsers

Description.

The main objective of ASP.NET MVC 4 is making to develop mobile web applications easily.Other than
mobile web applications It’s focus is also on better HTML5 support and making ASP.NET MVC web
application cloud ready.

By using new features of ASP.NET MVC 4 you can develop web applications that can work well across
different desktop web browsers and mobile devices.

2. What is Web API ‘s in Asp.Net MVC 4 ?

Ans.

 Web API is a new framework for consuming & building HTTP Services.

 Web API supports wide range of clients including different browsers and mobile devices.

 It is very good platform for developing RESTful services since it talk’s about HTTP.

3. What is the use of web API ? Why Web API needed, If you have already RESTful services using WCF
?

Ans. Yes, we can still develop the RESTful services with WCF, but there are two main reasons that
prompt users to use Web API instead of RESTful services.

 ASP.NET Web API is included in ASP.NET MVC which obviously increases TDD (Test Data
Driven) approach in the development of RESTful services.
 For developing RESTful services in WCF you still needs lot of config settings, URI templates,
contract’s & endpoints which developing RESTful services using web API is simple.

4. What are the new enhancements done in default project template of ASP.NET MVC 4?

Ans.

 Adaptive rendering for Nice Look & Feel

 Modern Looking for Mobile & Desktop browser

The new enhanced default project template came up with modern looking. Along with some cosmetic
enhancements, it also employs new adaptive rendering to look nice in both desktop and mobile browsers
without need of any kind of additional customization.

5. Why we need a separate mobile project template, while we can render our web application in mobile
(What’s new in MVC 4 Mobile template) ?

Ans.

 Smart Phones & tablets touch got smart by using new jQuery.Mobile.MVC NuGet pacage.

The mobile project template touch optimized UI by using jQuery.Mobile.MVC NuGet Package for tablets
and smart phones.

6. What is the use of Display Modes?

Ans.

 View can be changed automatically based on browser(For mobile and desktop browser’s)

Display Modes is newly added feature in ASP.NET MVC 4. Views selected automatically by application
depending on the browser. Example: If a desktop browser requests login page of an application it will
return Views\Account\Login.cshtml view & if a mobile browser requests home page it will return Views\
Account\Login.mobile.cshtml view.

7. What are the main features of ASP.NET MVC 4 used by ASP.NET Web API?

Ans.

 Routing changes: ASP.NET Web API uses same convention for config mapping that ASP.NET
MVC provides.

 Model Binding & Validation: ASP.NET Web API uses same model binding functionality, but
HTTP specific context related operations only.

 Filters: The ASP.NET Web API uses most of built-in filters from MVC.

 Unit Testing: Now Unit testing based on MVC, strongly unit testable.

8. What are Bundling & Minification features in ASP.NET MVC 4?


Ans. Bundling & Minification reduces number of HTTP requests. Bundling & Minification combines
individual files into single. Bundled file for CSS & scripts and then it reduce’s overall size by minifying
the contents of the bundle.

9 . What are the difference between asynchronous controller implementation b/w ASP.NET MVC 3 &
ASP.NET MVC 4? Can you explain in detail?

Ans. There is major difference is on implementation mechanism between ASP.NET MVC 3 and
ASP.NET MVC 4.

In ASP.NET MVC 3, to implement async controller or methods we need to derive controller from
AsyncController rather than from normal plain Controller class. We need to create 2 action methods
rather than one. First with suffix ‘Async’ keyword & second with ‘Completed’ suffix.

In ASP.NET MVC 4 you need not to declare 2 action method. One can serve the purpouse. MVC 4 using
.Net Framework 4.5 support for asynchronous communication.

10. Is MVC 4 supporting Windows Azure SDK (Software Development Kit) ?

Ans. Yes, MVC 4 is supporting Windows Azure SDK version 1.6 or higher.

What are the 3 main components of an ASP.NET MVC application?

1. M - Model

2. V - View

3. C - Controller

In which assembly is the MVC framework defined?

System.Web.Mvc

Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?

Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.

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

Model: Model represents the application data domain. In short the applications business logic is contained
with in the model.
View: Views 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: 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 greatest advantage of using asp.net mvc over asp.net webforms?

It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET
Webforms?

ASP.NET MVC

What are the advantages of ASP.NET MVC?

1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.

2. Complex applications can be easily managed

3. Seperation of concerns. Different aspects of the application can be divided into Model, View and
Controller.

4. ASP.NET MVC views are light weight, as they donot use viewstate.

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.

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.
What is the role of a controller in an MVC application?

The controller responds to user interactions, with the application, by selecting the action method to
execute and alse selecting the view to render.

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?

The following are just a few return types of a controller action method. In general an action method can
return an instance of a any class that derives from ActionResult class.

1. ViewResult

2. JavaScriptResult

3. RedirectResult

4. ContentResult

5. JsonResult

What is the significance of NonActionAttribute?

In general, all public methods of a controller class are treated as action methods. If you want prevent this
default behaviour, just decorate the public method with NonActionAttribute.

What is the significance of ASP.NET routing?

ASP.NET MVC uses ASP.NET routing, to map 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.

What are the 3 segments of the default route, that is present in an ASP.NET MVC application?

1st Segment - Controller Name

2nd Segment - Action Method Name


3rd Segment - Parameter that is passed to the action method

Example: http://pragimtech.com/Customer/Details/5

Controller Name = Customer

Action Method Name = Details

Parameter Id = 5

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.

What is the adavantage of using ASP.NET routing?

In an ASP.NET web application that does not make use of routing, an incoming browser request should
map to a physical file. If the file does not exist, we get page not found error.

An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map
to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are
descriptive of the user's action and therefore are more easily understood by users.

What are the 3 things that are needed to specify a route?

1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the
request handler without requiring a query string.

2. Handler - The handler can be a physical file such as an .aspx file or a controller class.

3. Name for the Route - Name is optional.

Is the following route definition a valid route definition?

{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter
between the placeholders. Therefore, routing cannot determine where to separate the value for the
controller placeholder from the value for the action placeholder.

What is the use of the following default route?

{resource}.axd/{*pathInfo}

This route definition, prevent requests for the Web resource files such as WebResource.axd or
ScriptResource.axd from being passed to a controller.

What is the difference between adding routes, to a webforms application and to an mvc application?

To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class,
where as to add routes to an MVC application we use MapRoute() method.

How do you handle variable number of segments in a route definition?

Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all
parameter.

controller/{action}/{*parametervalues}

What are the 2 ways of adding constraints to a route?

1. Use regular expressions

2. Use an object that implements IRouteConstraint interface

Give 2 examples for scenarios when routing is not applied?

1. A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by
setting the RouteExistingFiles property of the RouteCollection object to true.

2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent
routing from handling certain requests.

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

What are the different types of filters, in an asp.net mvc application?

1. Authorization filters

2. Action filters

3. Result filters

4. Exception filters

Give an example for Authorization filters in an asp.net mvc application?

1. RequireHttpsAttribute

2. AuthorizeAttribute

Which filter executes first in an asp.net mvc application?

Authorization filter

What are the levels at which filters can be applied in an asp.net mvc application?

1. Action Method

2. Controller

3. Application
[b]Is it possible to create a custom filter?[/b]

Yes

What filters are executed in the end?

Exception Filters

Is it possible to cancel filter execution?

Yes

What type of filter does OutputCacheAttribute class represents?

Result Filter

What are the 2 popular asp.net mvc view engines?

1. Razor

2. .aspx

What symbol would you use to denote, the start of a code block in razor views?

What symbol would you use to denote, the start of a code block in aspx views?

<%= %>

In razor syntax, what is the escape sequence character for @ symbol?

The escape sequence character for @ symbol, is another @ symbol

When using razor views, do you have to take any special steps to proctect your asp.net mvc application
from cross site scripting (XSS) attacks?
No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site
scripting (XSS) attacks.

When using aspx view engine, to have a consistent look and feel, across all pages of the application, we
can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views?

To have a consistent look and feel when using razor views, we can make use of layout pages. Layout
pages, reside in the shared folder, and are named as _Layout.cshtml

What are sections?

Layout pages, can define sections, which can then be overriden by specific views making use of the
layout. Defining and overriding sections is optional.

What are the file extensions for razor views?

1. .cshtml - If the programming lanugaue is C#

2. .vbhtml - If the programming lanugaue is VB

How do you specify comments using razor syntax?

Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end. An
example is shown below.

@* This is a Comment *@

Question 1: What does MVC stand for>

Answer: Model-View-Controller.

Question 2: What are three main components or aspects of MVC?

Answer: Model-View-Controller
Question 3: Which namespace is used for ASP.NET MVC? Or which assembly is used to define the
MVC framework?

Answer: System.Web.Mvc

Question 4: What is the default view engine in ASP.NET MVC?

Answer: Web Form(ASPX) and Razor View Engine.

Question 5: Can we remove the default View Engine?

Answer: Yes, by using the following code:

1. protected void Application_Start()

2. {

3. ViewEngines.Engines.Clear();

4. }

Question 6: Can we have a Custom View Engine?

Answer: Yes, by implementing the IViewEngine interface or by inheriting from the


VirtualPathProviderViewEngine abstract class.

Question 7: Can we use a third-party View Engine?

Answer: Yes, ASP.NET MVC can have Spark, NHaml, NDjango, Hasic, Brail, Bellevue, Sharp Tiles,
String Template, Wing Beats, SharpDOM and so on third-party View Engine.
Question 8: What are View Engines?

Answer: View Engines are responsible for rendering the HTML from your views to the browser.

Question 9: What is Razor Engine?

Answer: The Razor view engine is an advanced view engine from Microsoft, packaged with MVC 3.
Razor uses an @ character instead of aspx's <% %> and Razor does not require you to explicitly close the
code-block.

Question 10: What is scaffolding?

Answer: Quickly generating a basic outline of your software that you can then edit and customize.

Question 11: What is the name of Nuget scaffolding package for ASP.NET MVC3 scaffolding?

Answer: MvcScaffolding

Question 12: Can we share a view across multiple controllers?

Answer: Yes, it is possible to share a view across multiple controllers by putting a view into the shared
folder.

Question 13: What is unit testing?

Answer: The testing of every smallest testable block of code in an automated manner. Automation makes
things more accurate, faster and reusable.
Question 14: Is unit testing of MVC application possible without running the controller?

Answer: Yes, by the preceding definition.

Question 15: Can you change the action method name?

Answer: Yes, we can change the action method name using the ActionName attribute. Now the action
method will be called by the name defined by the ActionName attribute.

1. [ActionName("DoAction")]

2. public ActionResult DoSomething()

3. {

4. /TODO:

5. return View();

6. }

Question 16: How to prevent a controller method from being accessed by an URL?

Answer: By making the method private or protected but sometimes we need to keep this method public.
This is where the NonAction attribute is relevant.

Question 17: What are the features of MVC5?

Answer:

• Scaffolding

• ASP.NET Identity

• One ASP.NET

• Bootstrap
• Attribute Routing

• Filter Overrides

Question 18: What are the various types of filters in an ASP.NET MVC application?

Answer:

• Authorization filters

• Action filters

• Result filters

• Exception filters

Question 19: If there is no match in the route table for the incoming request's URL, which error will
result?

Answer: 404 HTTP status code

Question 20: How to enable Attribute Routing?

Answer: By adding a Routes.MapMvcAttributeRoutes() method to the RegisterRoutes() method of the


RouteConfig.cs file.

Q.What is MVC routing?

A. URL Routing is the routing done by MVC which is , When we type something in the url , then it will
first invoke the RouteConfig.RegisterRoutes(RouteTable.Routes);

which is in Global.asax.cs Application_Start() method , then it will call the

public static void RegisterRoutes(RouteCollection

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

);

Which is in App_start=>RouteConfig class you can find out the RegisterRoutes method here . Here we
can define the structure of our url and here it will decide which controller and action should be invoked.
This process is url Routing

Q.What if URL rewriting?

A.URL rewriting is entire diff concept Let us assume our controller name is Customer and action name is
Login when we run the application our url will be like the belowhttp://Localhost:233/Customer/Loginbut
the client needed http://Localhost:233/Login only, for SEO purposes In order to achieve this we have to
rewrite the url by keeping the same controller and action name to know more about url rewriting i have
explained attribute rewriting inhttp://grandhah.blogspot.in/2015/07/url-rewriting-in-mvc-4-attribute-
routing.html

Q. What is MVC (Model-View-Controller)

A. MVC is an architectural pattern which separates the representation and user interaction. It’s divided
into three broader sections, Model, View, and Controller. Below is how each one of them handles the
task.

• The View is responsible for the look and feel.

• Model represents the real world object and provides data to the View.

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

Q.MVC Life cycle

A. Any web based application has mainly two steps one is analyzing the request and second one is
creating response according to the request, MVC also do the same thing

Creating the request:-


Fill route :- MVC requests are mapped into route table, The actual url contains the controller name and
action name ,the first thing creating the request is filling the route table with route which is happen in the
global.asax

Fetch route:-Depending on the url, search the route table to create RouteData which has information of
controller and action name which has to be invoke

Request context created:-Routedata object id used to create requestcontext object

Controller instance create :-RequestObject is send to MvcHandler for creating instance, once controller
class object is created it calls the "Execute" of controller class

Creating response object:-Executing the action and sending the response as result to the view .

Q.Difference between ASP.NET MVC and ASP.NET WebForms

ASP.NET Web Forms uses Page controller pattern approach for rendering layout, whereas ASP.NET
MVC uses Front controller approach. In case of Page controller approach, every page has its own
controller, i.e., code-behind file that processes the request. On the other hand, in ASP.NET MVC, a
common controller for all pages processes the requests.

Q.What is the difference between viewdata,Viewbag and tempdata

As http is a stateless protocol , we are not able to maintain the state , That is why they implemented
different techniques Session,etc. But in MVC, Microsoft introduced different objects to maintain state.

Viewdata:-Used to communicate between controller and corresponding view

Life time ,exists only when the view loads.

ViewBag:-Nothing but a collection of viewdata, ViewData is a dictionary object while ViewBag is a


dynamic property we can accessible using string key and requires typecasting Life time, exists only when
the view loads.

TempData:-We can pass data from one action to another it can maintain data between redirects Life time
is tempdata become null when it is used once.
Q.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.

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

1. ViewResult

2. JavaScriptResult

3. RedirectResult

4. ContentResult

5. JsonResult

Q.What is the significance of NonActionAttribute?

This attribute indicates that the controller method is not an action method

Ref:- https://msdn.microsoft.com/en-us/library/system.web.mvc.nonactionattribute(v=vs.118).aspx

By default all of the public method which is defined in the controller , is considered as an action method ,
If you want to define an public method which is not an action method then use the Non-action attribute

Q.What are the different types of filters, in an asp.net mvc application?

Sometimes you want to perform a logic to be run even before the action method invokes , for that purpose
, ASP.NET mvc provides filters. Filters are custom classes which provide both declarative and
programmatic means to add preaction post action behavior to controller action methods.

Ref:- https://msdn.microsoft.com/en-us/library/gg416513(VS.98).aspx

Type of filters

Now taking this discussion further, Let us first discuss the various types of filters that can be implemented
to inject custom processing logic.
Authorization filter

Action filter

Result filter

Exception filter

Q. What is the meaning of Unobtrusive JavaScript?

This is a general term that conveys a general philosophy, similar to the term REST (Representational
State Transfer). Unobtrusive JavaScript doesn't intermix JavaScript code in your page markup.

Eg : Instead of using events like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by
their ID or class based on the HTML5 data- attributes.

Q.MVC 4 New features

MVC 4 features having two category MVC Framework and mvc project template

MVC 4 Framework

1) Add controller to the other folders

2)Task support for asynchronous controllers

3)Bundling and magnification

4)Enabling Logins from Facebook and other websites using OAuthconfig

5)App_Start folder separated classes

6)Display modes using this we could select the different browsers


7)Azure SDK

8)Database migration

MVC Project template

1)ASP.NET Web API

2)Mobile Project template

3)Empty Project template

4)Enhanced default project template

Q.What are the new features in Asp.Net MVC5 ?

Introducing One ASP.NET

Introducing Asp.Net One Identity

Introducing Bootstrap in the MVC template

Introducing Filter overrides (Overriding filters)

Introducing Authentication Filters

Introducing Web API 2

Introducing OAuth 2.0 Authorization in MVC 5

OData Improvements in MVC 5(Full support for $select, $expand, $batch, and $value)

Introducing ASP.NET SignalR 2.0

ASP.NET WEB API 2

Attribute routing

Q.What’s Bootstrap is new MVC 5 ?


MVC project template is updated in MVC 5 to use Bootstrap for better look and feel. Now you can easily
customize. For more information

Bootstrap In Short:

With the updated MVC template, You can do Customization very easily

Better look and feel.

create our own, simply extend

routes.MapAttributeRoutes(myConfig =>

myConfig.AddTranslationProvider(new MyCustomTranslationProvider());

});

ROUTE CONVENTION ATTRIBUTE ATTRIBUTE

public class MyRouteConventionAttribute : RouteConventionAttributeBase

public override IEnumerable

GetRouteAttributes(MethodInfo actionMethod)

// TODO: Yield IRouteAttributes (GET/POST/PUT/DELETE/Route).

SUBDOMAIN ROUTING

Wc can map our ASP.NET MVC areas to sub-domains by using the Sub-domain property of the
RouteAreaAttribute. Doing so ensures that the routes for the area are matched only when requests are
made to the specified sub-domain. Here’s how:
[RouteArea(“Users”, Subdomain = “users”)]

public class SubdomainController : Controller

[GET(“”)]

public ActionResult Index() { /* … */ }

Q.Is OAuth 2.0 support’s for Web API and Single Page Application ?

The MVC Web API and Single Page Application project templates now support authorization using
OAuth 2.0. OAuth 2.0 is a authorization framework for authorizing client access to protected resources. It
works for a variety of clients like for different browsers & mobile devices.

Q.What are the OData Improvements ?

Full Support for $select, $expand, $batch & $value

Much improved extensibility

Type less support (No need to define CLR types)

Ref :- http://onlinedotnet.com/mvc-5-interview-questions-and-answers/

Q.How to use Cookie in MVC.

HttpCookie cook = new HttpCookie("Transfer");

cook.Expires = DateTime.Now.AddSeconds(1);

cook.Value = "from transfer cookies";


Response.Cookies.Add(cook);

Q.What is _ViewSatrt.cshtml

Starting from mvc 3 we could add a file called Viewstart.cshtml.

View start file can be used as to define common Layout page , we could pragmatically change the layout
page according to our needs.It will execute when each view is loading View start also loads so no need of
giving any layout in each view

This enable a lot of flexibility.And avoid repeating common code in view start file

Q.What is the difference between each version of MVC 2, 3 , 4, 5 and 6?

MVC 6

ASP.NET MVC and Web API has been merged in to one.

Dependency injection is inbuilt and part of MVC.

Side by side - deploy the runtime and framework with your application

Everything packaged with NuGet, Including the .NET runtime itself.

New JSON based project structure.

No need to recompile for every change. Just hit save and refresh the browser.

Compilation done with the new Roslyn real-time compiler.

vNext is Open Source via the .NET Foundation and is taking public contributions.

vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.

MVC 5
One ASP.NET

Attribute based routing

Asp.Net Identity

Bootstrap in the MVC template

Authentication Filters

Filter overrides

MVC 4

ASP.NET Web API

Refreshed and modernized default project templates

New mobile project template

Many new features to support mobile apps

Enhanced support for asynchronous methods

MVC 3

Razor

Readymade project templates

HTML 5 enabled templates

Support for Multiple View Engines

JavaScript and Ajax

Model Validation Improvements

MVC 2

Client-Side Validation

Templated Helpers
Areas

Asynchronous Controllers

Html.ValidationSummary Helper Method

DefaultValueAttribute in Action-Method Parameters

Binding Binary Data with Model Binders

DataAnnotations Attributes

Model-Validator Providers

New RequireHttpsAttribute Action Filter

Templated Helpers

Display Model-Level Errors

Ref:- http://www.codeproject.com/Articles/556995/ASP-NET-MVC-interview-questions-with-
answers#WhatisthedifferencebetweeneachversionofMVC2,3,4,5and6

Q.What is html helpers

eg:-@Html.TextBox("Name")

Html helpers will help us to create different html controls in the view

Q.What is data annotation validation in MVC

In MVC.net we could do the validation using data annotation which is so simple and very easy to
implement .we can decorate the viewmodel properties with Dataannotation class which we need
validation .

The common annotation present are

Required – Indicates that the property is a required field

DisplayName – Defines the text we want used on form fields and validation messages
StringLength – Defines a maximum length for a string field

Range – Gives a maximum and minimum value for a numeric field

Bind – Lists fields to exclude or include when binding parameter or form values to model properties

ScaffoldColumn – Allows hiding fields from editor forms

Please refer a simple example how to use the annotation in viewmodel

public class RegistrationViewModel

[Required]

[Display(Name = "User name")]

public string UserName { get; set; }

[Required]

[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength =
6)]

[DataType(DataType.Password)]

[Display(Name = "Password")]

public string Password { get; set; }

[DataType(DataType.Password)]

[Display(Name = "Confirm password")]

[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]

public string ConfirmPassword { get; set; }

Q.What is dependency injuction


In Object oriented programming, the objects works together in a collaboration model where these are
contributes and consumers . These process create dependency between object and components on time
being theses dependencies are difficult to manage . These scattered dependency will grow un-manageable

The dependency injunction is a particular type of implementation of inversion of control means objects
cannot create another objects an outside component will create the objects mainly injecting through the
constructor. This is called dependency injunction.

Advantage : Reduces class coupling

Increases code reusing

Improves code maintainability

Improves application testing

Q.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 filters)

Model binders (registering and injecting)

Model validation providers (registering and injecting)

Model metadata providers (registering and injecting)

Value providers (registering and injecting)


Q.What is AuthConfig.cs in MVC4

AuthConfig.cs is used to configure security settings, including sites for OAuth login.

Q. 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.

Q. 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.

Q. What is RouteConfig.cs in MVC4

RouteConfig.cs holds the granddaddy of the MVC config statements, Route configuration.

Q.What is WebApiConfig.cs in MVC4

Used to register Web API routes, as well as set any additional Web API configuration settings.

What are routing in MVC?

Routing helps you to define user friendly URL structure and map those URL structure to the controller.
For instance let's say we want that when any user types "http://localhost/View/ViewCustomer/" , it goes
to the "Customer" Controller and invokes "DisplayCustomer" action.This is defined by adding an entry in
to the "routes" collection using the "maproute" function. Below is the under lined code which shows how
the URL structure and mapping with controller and action is defined.

Where is the route mapping code written?

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

Can we map multiple URL's to the same action?

Yes , you can , you just need to make two entries with different key names and specify the same
controller and action.

Explain attribute based routing in MVC?

This is a feature introduced in MVC 5. By using the "Route" attribute we can define the URL structure.
For example in the below code we have decorated the "GotoAbout" action with the route attribute. The
route attribute says that the "GotoAbout" can be invoked using the URL structure "Users/about".

What is the advantage of defining route structures in the code?

Most of the time developers code in the action methods. Developers can see the URL structure right
upfront rather than going to the "routeconfig.cs" and see the lengthy codes. For instance in the below code
the developer can see right upfront that the "GotoAbout" action can be invoked by four different URL
structure.

This is much user friendly as compared to scrolling through the "routeconfig.cs" file and going through
the length line of code to figure out which URL structure is mapped to which action
1. What is MVC?

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.

2. Explain MVC design pattern?

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.

Today, this pattern is used by many popular framework like as Ruby on Rails, Spring Framework, Apple
iOS Development and ASP.NET MVC.

Asp.net MVC Design Pattern in .NET

3. What is Domain Driven Design and Development?

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.

4. What is MVP pattern?

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.

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

• User interacts with the View.

• There is one-to-one relationship between View and Presenter means one View is mapped to only
one Presenter.
• View has a reference to Presenter but View has not reference to Model.

• Provides two way communication between View and Presenter.

5. What is MVVM pattern?

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.

This pattern is commonly used by the WPF, Silverlight, Caliburn, nRoute etc.

Key Points about MVVM Pattern

• User interacts with the View.

• There is many-to-one relationship between View and ViewModel means many View can be
mapped to one ViewModel.

• View has a reference to ViewModel but View Model has no information about the View.

• Supports two-way data binding between View and ViewModel.

6. What is ASP.NET MVC?

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.

7. How MVC pattern works in ASP.NET MVC?

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:

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
stronglytyped 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.

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.

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.

8. How Model, View and Controller communicate with each other in ASP.NET MVC?

There are following rules for communication among Model, View and Controller:

• User interacts with the Controller.

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

• Controller and View can have a reference to model.

• Controller and View can talk to each other.

• Model and View cannot talk to each other directly. They communicate to each other with the help
of controller.
9. What are advantages of ASP.NET MVC?

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
aspectsModel, 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.

10. Explain brief history of ASP.NET MVC?

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

• 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

• 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

11. What is difference between 3-layer architecture and MVC architecture?


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.

12. What is difference between ASP.NET WebForm and ASP.NET MVC?

The main differences between ASP.NET Web Form and ASP.NET MVC are given below:

ASP.NET WebForms 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 Web Form has state management (like as view state, session) techniques. ASP.NET
MVC has no automatic state management techniques.

ASP.NET Web Form has file-based URLs means file name exist in the URLs must have its physically
existence. ASP.NET MVC has route-based URLs means URLs are divided into controllers and
actions and moreover it is based on controller not on physical file.

ASP.NET Web Form follows WebForm Syntax ASP.NET MVC follow customizable syntax (Razor as
default)

In ASP.NET Web Form, Web Forms (ASPX) i.e. views are tightly coupled to Code behind (ASPX.CS)
i.e. logic. In ASP.NET MVC, Views and logic are kept separately.
ASP.NET Web Form has Master Pages for consistent look and feels. ASP.NET MVC has Layouts for
consistent look and feels.

ASP.NET Web Form has User Controls for code reusability. ASP.NET MVC has Partial Views for
code re-usability.

ASP.NET Web Form has built-in data controls and best for rapid development with powerful data access
ASP.NET MVC is lightweight, provide full control over mark-up and support many features that
allow fast & agile development. Hence it is best for developing interactive web application with latest
web standards.

ASP.NET Web Form is not Open Source. ASP.NET Web MVC is an Open Source.

13. What is ViewModel in ASP.NET MVC?

In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-
typed view. It is used to pass data from controller to strongly-typed view.

Key Points about ViewModel

 ViewModel contain fields that are represented in the view (for LabelFor, EditorFor, DisplayFor
helpers)

 ViewModel can have specific validation rules using data annotations.

 ViewModel can have multiple entities or objects from different data models or data source.

14. What is Routing in ASP.NET MVC?

Routing is a pattern matching system that monitor the incoming request and figure out what to do with
that request. At runtime, Routing engine use the Route table for matching the incoming request's URL
pattern against the URL patterns defined in the Route table. You can register one or more URL patterns to
the Route table at Application_Start event
When the routing engine finds a match in the route table for the incoming request's URL, it forwards the
request to the appropriate controller and action. If there is no match in the route table for the incoming
request's URL, it returns a 404 HTTP status code.

15. Explain ASP.NET MVC pipeline?

The detail ASP.NET MVC pipeline is given below :

1. Routing - Routing is the first step in ASP.NET MVC pipeline. Typically, it is a pattern matching
system that matches the incoming request to the registered URL patterns in the Route Table.

The UrlRoutingModule(System.Web.Routing.UrlRoutingModule) is a class which matches an incoming


HTTP request to a registered route pattern in the RouteTable(System.Web.Routing.RouteTable).

2. Controller Initialization - The MvcHandler initiates the real processing inside ASP.NET MVC
pipeline by using ProcessRequest method. This method uses the IControllerFactory instance (default is
System.Web.Mvc.DefaultControllerFactory) to create corresponding controller.

3. Action Execution – Action execution occurs in the following steps:

 When the controller is initialized, the controller calls its own InvokeAction() method by passing
the details of the chosen action method. This is handled by the IActionInvoker.

 After chosen of appropriate action method, model binders(default is


System.Web.Mvc.DefaultModelBinder) retrieves the data from incoming HTTP request and do the data
type conversion, data validation such as required or date format etc. and also take care of input values
mapping to that action method parameters.

 Authentication Filter was introduced with ASP.NET MVC5 that run prior to authorization filter.
It is used to authenticate a user. Authentication filter process user credentials in the request and provide a
corresponding principal. Prior to ASP.NET MVC5, you use authorization filter for authentication and
authorization to a user.

 By default, Authenticate attribute is used to perform Authentication. You can easily create your
own custom authentication filter by implementing IAuthenticationFilter.

 Authorization filter allow you to perform authorization process for an authenticated user. For
example, Role based authorization for users to access resources.

 By default, Authorize attribute is used to perform authorization. You can also make your own
custom authorization filter by implementing IAuthorizationFilter.
 Action filters are executed before (OnActionExecuting) and after (OnActionExecuted) an action
is executed. IActionFilter interface provides you two methods OnActionExecuting and
OnActionExecuted methods which will be executed before and after an action gets executed respectively.
You can also make your own custom ActionFilters filter by implementing IActionFilter. For more about
filters refer this article Understanding ASP.NET MVC Filters and Attributes

 When action is executed, it process the user inputs with the help of model (Business Model or
Data Model) and prepare Action Result.

4. Result Execution - Result execution occurs in the following steps:

 Result filters are executed before (OnResultExecuting) and after (OnResultExecuted) the
ActionResult is executed. IResultFilter interface provides you two methods OnResultExecuting and
OnResultExecuted methods which will be executed before and after an ActionResult gets executed
respectively. You can also make your own custom ResultFilters filter by implementing IResultFilter.

 Action Result is prepared by performing operations on user inputs with the help of BAL or DAL.
The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult,
ContentResult, JsonResult, FileResult and EmptyResult.

 Various Result type provided by the ASP.NET MVC can be categorized into two category-
ViewResult type and NonViewResult type. The Result type which renders and returns an HTML page to
the browser, falls into ViewResult category and other result type which returns only data either in text
format, binary format or a JSON format, falls into NonViewResult category.

5. View Initialization and Rendering - View Initialization and Rendering execution occurs in the
following steps:

 ViewResult type i.e. view and partial view are represented by IView (System.Web.Mvc.IView)
interface and rendered by the appropriate View Engine.

 This process is handled by IViewEngine (System.Web.Mvc.IViewEngine) interface of the view


engine. By default ASP.NET MVC provides WebForm and Razor view engines. You can also create your
custom engine by using IViewEngine interface and can registered your custom view engine in to your
ASP.NET MVC application as shown below:

 Html Helpers are used to write input fields, create links based on the routes, AJAX-enabled
forms, links and much more. Html Helpers are extension methods of the HtmlHelper class and can be
further extended very easily. In more complex scenario, it might render a form with client side validation
with the help of JavaScript or jQuery

16. How to define a route in ASP.NET MVC?

You can define a route in ASP.NET MVC as given below:


public static void RegisterRoutes(RouteCollection routes)

routes.MapRoute(

"Default", // Route name

"{controller}/{action}/{id}", // Route Pattern

new

controller = "Home",

action = "Index",

id = UrlParameter.Optional

} // Default values for above defined parameters );

protected void Application_Start()

RegisterRoutes(RouteTable.Routes);

//TODO:

Always remember route name should be unique across the entire application. Route name can’t be
duplicate. In above example we have defined the Route Pattern {controller}/{action}/{id} and also
provide the default values for controller, action and id parameters. Default values means if you will not
provide the values for controller or action or id defined in the pattern then these values will be serve by
the routing system. Suppose your webapplication is running on www.example.com then the url pattren for
you application will be www.example.com/{controller}/{action}/{id}. Hence you need to provide the
controller name followed by action name and id if it is required. If you will not provide any of the value
then default values of these parameters will be provided by the routing system. Here is a list of URLs that
match and don't match this route pattern.

Request URL Parameters


http://example.com/ controller=Home, action=Index, id=none, Since default value of controller and
action are Home and Index respectively

http://example.com/Admin controller=Admin, action=Index, id=none, Since default value of action


is Inde

http://example.com/Admin/Product controller=Admin, action=Product, id=none

http://example.com/Admin/Product/1 controller=Admin, action=Product, id=1

http://example.com/Admin/Product/SubAdmin/1No Match Found

http://example.com/Admin/Product/SubAdmin/Add/1 No Match Found

Note : Always put more specific route on the top order while defining the routes, since routing system
check the incoming URL pattern form the top and as it get the matched route it will consider that. It will
not checked further routes after matching pattern.

17. What is Attribute Routing and how to define it?

ASP.NET MVC5 and WEB API 2 supports a new type of routing, called attribute routing. In this routing,
attributes are used to define routes. Attribute routing provides you more control over the URIs by defining
routes directly on actions and controllers in your ASP.NET MVC application and WEB API.

1. Controller level routing – You can define routes at controller level which apply to all actions within the
controller unless a specific route is added to an action.

[RoutePrefix("MyHome")]

[Route("{action=index}")] //default action

public class HomeController : Controller

//new route: /MyHome/Index

public ActionResult Index()

return View();

}
//new route: /MyHome/About

public ActionResult About()

ViewBag.Message = "Your application description page.";

return View();

//new route: /MyHome/Contact

public ActionResult Contact()

ViewBag.Message = "Your contact page.";

return View();

2. Action level routing – You can define routes at action level which apply to a specific action with in the
controller.

public class HomeController : Controller

[Route("users/{id:int:min(100)}")] //route: /users/100

public ActionResult Index(int id)

//TO DO:

return View();

[Route("users/about")] //route" /users/about


public ActionResult About()

ViewBag.Message = "Your application description page.";

return View();

//route: /Home/Contact

public ActionResult Contact()

ViewBag.Message = "Your contact page.";

return View();

Note :

 Attribute routing should configure before the convention-based routing.

 When you combine attribute routing with convention-based routing, actions which do not have
Route attribute for defining attribute-based routing will work according to convention-based routing. In
above example Contact action will work according to convention-based routing.

 When you have only attribute routing, actions which do not have Route attribute for defining
attribute-based routing will not be the part of attribute routing. In this way they can’t be access from
outside as a URI.

18. When to use Attribute Routing?

The convention-based routing is complex to support certain URI patterns that are common in RESTful
APIs. But by using attribute routing you can define these URI patterns very easily. For example,
resources often contain child resources like Clients have orders, movies have actors, books have authors
and so on. It’s natural to create URIs that reflects these relations like as: /clients/1/orders. This type of
URI is difficult to create using convention-based routing. Although it can be done, the results don’t scale
well if you have many controllers or resource types. With attribute routing, it’s pretty much easy to define
a route for this URI. You simply add an attribute to the controller action as:

[Route("clients/{clientId}/orders")]

public IEnumerable<order> GetOrdersByClient(int clientId)

//TO DO

</order>

19. How to enable Attribute Routing in ASP.NET MVC?

Enabling attribute routing in your ASP.NET MVC5 application is simple, just add a call to
routes.MapMvcAttributeRoutes() method with in RegisterRoutes() method of RouteConfig.cs file

public class RouteConfig

public static void RegisterRoutes(RouteCollection routes)

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

//enabling attribute routing

routes.MapMvcAttributeRoutes();

You can also combine attribute routing with convention-based routing.

public class RouteConfig

{
public static void RegisterRoutes(RouteCollection routes)

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

//enabling attribute routing

routes.MapMvcAttributeRoutes();

//convention-based routing

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id =

UrlParameter.Optional });

20. How to define Attribute Routing for Area in ASP.NET MVC?

You can also define attribute routing for a controller that belongs to an area by using the RouteArea
attribute. When you define attribute routing for all controllers with in an area, you can safely remove the
AreaRegistration class for that area.

[RouteArea("Admin")]

[RoutePrefix("menu")]

[Route("{action}")]

public class MenuController : Controller

// route: /admin/menu/login

public ActionResult Login()

return View();
}

// route: /admin/menu/products

[Route("products")]

public ActionResult GetProducts()

return View();

// route: /categories

[Route("~/categories")]

public ActionResult Categories()

return View();

21. What is difference between Routing and URL Rewriting?

Many developers compare routing to URL rewriting since both look similar and can be used to make SEO
friendly URLs. But both the approaches are very much different. The main difference between routing
and url rewriting is given below:

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

 URL rewriting rewrites your old url to new one while routing never rewrite your old url to new
one but it map to the original route.

22. What is Route Constraints in ASP.NET MVC?


Route constraints is way to put some validation around the defined route.Creating Route Constraints

Suppose we have defined the following route in our application and you want to restrict the incoming
request url with numeric id only.Now let's see how to do it with the help of regular expression.

public static void RegisterRoutes(RouteCollection routes)

routes.MapRoute(

"Default", // Route name

"{controller}/{action}/{id}", // Route Pattern

new

controller = "Home",

action = "Index",

id = UrlParameter.Optional

} // Default values for parameters

);

Restrict to numeric id only

public static void RegisterRoutes(RouteCollection routes)

routes.MapRoute(

"Default", // Route name

"{controller}/{action}/{id}", // Route Pattern

new

controller = "Home",

action = "Index",
id = UrlParameter.Optional

}, // Default values for parameters

new { id = @"\d+" } //Restriction for id

);

Now for this route, routing engine will consider only those URLs which have only numeric id like as
http://example.com/Admin/Product/1 else it will considers that url is not matched with this route.

23. 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.

24. What are important namespaces in ASP.NET MVC?

There are some important namespaces as given below:

 System.Web.Mvc - 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.

 System.Web.Mvc.Ajax - This 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.

 System.Web.Mvc.Html – This 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.

25. What is View Engine?

A View Engine is a MVC subsystem which has its own markup syntax. It is responsible for converting
serverside template into HTML markup and rendering it to the browser. Initially, ASP.NET MVC ships
with one view engine, web forms (ASPX) and from ASP.NET MVC3 a new view engine, Razor is
introduced. With ASP.NET MVC, you can also use other view engines like Spark, NHaml etc.

26. How View Engine works?

Each view engine has following three main components:


1. ViewEngine class - This class implements the IViewEngine interface and responsible for locating
view templates.

2. View class - This class implements the IView interface and responsible for combining the
template with data from the current context and convert it to output HTML markup.

3. Template parsing engine - This parses the template and compiles the view into executable code.

27. What is Razor View Engine?

Razor Engine is an advanced view engine that was introduced with MVC3. This is not a new language
but it is a new markup syntax. Razor has new and advance syntax that are compact, expressive and
reduces typing.Razor syntax are easy to learn and much clean than Web Form syntax. Razor uses @
symbol to write markup as:

Ex: Html.ActionLink("SignUp", "SignUp")

28. How to make Custom View Engine?

ASP.NET MVC is an open source and highly extensible framework. You can create your own View
engine by Implementing IViewEngine interface or by inheriting VirtualPathProviderViewEngine abstract
class.

public class CustomViewEngine : VirtualPathProviderViewEngine

public CustomViewEngine()

// Define the location of the View and Partial View

this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.html",

"~/Views/Shared/{0}.html" };

this.PartialViewLocationFormats = new string[] { "~/Views/{1}/{0}.html",

"~/Views/Shared/{0}.html" };

protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)


{

var physicalpath =

controllerContext.HttpContext.Server.MapPath(partialPath);

return new CustomView(physicalpath);

protected override IView CreateView(ControllerContext controllerContext, string viewPath, string


masterPath)

var physicalpath =

controllerContext.HttpContext.Server.MapPath(viewPath);

return new CustomView(physicalpath);

public class CustomView : IView

private string _viewPhysicalPath;

public CustomView(string ViewPhysicalPath)

_viewPhysicalPath = ViewPhysicalPath;

public void Render(ViewContext viewContext, System.IO.TextWriter writer)

//Load File

string rawcontents = File.ReadAllText(_viewPhysicalPath);


//Perform Replacements

string parsedcontents = Parse(rawcontents, viewContext.ViewData);

writer.Write(parsedcontents);

public string Parse(string contents, ViewDataDictionary viewdata)

return Regex.Replace(contents, "\\{(.+)\\}", m => GetMatch(m, viewdata));

public virtual string GetMatch(Match m, ViewDataDictionary viewdata)

if (m.Success)

string key = m.Result("$1");

if (viewdata.ContainsKey(key))

return viewdata[key].ToString();

return string.Empty;

29. How to register Custom View Engine in ASP.NET MVC?


To use your custom View Engine, you need to register it by using global.asax.cs file Application_Start()
method, so that the framework will use your custom View Engine instead of the default one.

protected void Application_Start()

//Register Custom View Engine

ViewEngines.Engines.Add(new CustomViewEngine());

//other code is removed for clarity

30. Can you remove default View Engine in ASP.NET MVC?

Yes, you can remove default view engines (Razor and WebForm) provided by ASP.NET MVC.

protected void Application_Start()

//Remove All View Engine including Webform and Razor

ViewEngines.Engines.Clear();

31. What is difference between Razor and WebForm engine?

The main differences between ASP.NET Web Form and ASP.NET MVC are given below:

Razor View Engine Webform View Engine

Razor Engine is an advanced view engine that was introduced with MVC3. This is not a new language
but it is a new markup syntax. Web Form Engine is the default view engine for the Asp.net MVC that is
included with Asp.net MVC from the beginning.

Razor Engine is an advanced view engine that was introduced with MVC3. This is not a new language
but it is a new markup syntax. Web Form Engine is the default view engine for the Asp.net MVC that is
included with Asp.net MVC from the beginning.

The namespace for Razor Engine is System.Web.Razor. The namespace for Webform Engine is
System.Web.Mvc.WebFormViewEngine.

The file extensions used with Razor Engine are different from Web Form Engine. It has .cshtml (Razor
with C#) or .vbhtml (Razor with VB) extension for views, partial views, editor templates and for layout
pages. The file extensions used with Web Form Engine are also like Asp.net Web Forms. It has .aspx
extension for views, .ascx extension for partial views & editor templates and .master extension for
layout/master pages.

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

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

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

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

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

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

32. What are HTML Helpers in ASP.NET MVC?

An HTML Helper is just a method that returns a HTML string. The string can represent any type of
content that you want. For example, you can use HTML Helpers to render standard HTML tags like
HTML <input>, <button> and <img> tags etc. You can also create your own HTML Helpers to render
more complex content such as a menu strip or an HTML table for displaying database data.

33. What are different types of HTML Helpers?

There are three types of HTML helpers as given below:

1. Inline Html Helpers - These are create in the same view by using the Razor @helper tag. These helpers
can be reused only on the same view

@helper ListingItems(string[] items)

{
<ol>

@foreach (string item in items)

<li>@item</li>

</ol>

<h3>Programming Languages:</h3>

@ListingItems(new string[] { "C", "C++", "C#" })

<h3>Book List:</h3>

@ListingItems(new string[] { "How to C", "how to C++", "how to C#" })

2. Built-In Html Helpers - Built-In Html Helpers are extension methods on the HtmlHelper class. The
Built-In Html helpers can be divided into three categories-• Standard Html Helpers - These helpers are
used to render the most common types of HTML elements like as HTML text boxes, checkboxes etc. A
list of most common standard html helpers is given below:

HTML Element Example

TextBox @Html.TextBox("Textbox1", "val") Output: <input id="Textbox1" name="Textbox1"


type="text" value="val" />

TextArea @Html.TextArea("Textarea1", "val", 5, 15, null) Output: <textarea cols="15"


id="Textarea1" name="Textarea1" rows="5">val</textarea>

Password @Html.Password("Password1", "val") Output: <input id="Password1"


name="Password1" type="password" value="val" />

Hidden Field @Html.Hidden("Hidden1", "val") Output: <input id="Hidden1" name="Hidden1"


type="hidden" value="val" />

CheckBox @Html.CheckBox("Checkbox1", false) Output: <input id="Checkbox1"


name="Checkbox1" type="checkbox" value="true" /> <input name="myCheckbox" type="hidden"
value="false" />

RadioButton @Html.RadioButton("Radiobutton1", "val", true) Output: <input checked="checked"


id="Radiobutton1" name="Radiobutton1" type="radio" value="val" /
Drop-down list @Html.DropDownList (“DropDownList1”, new SelectList(new [] {"Male", "Female"}))
Output: <select id="DropDownList1" name="DropDownList1"> <option>M</option>
<option>F</option> </select>

Multiple-select Html.ListBox(“ListBox1”, new MultiSelectList(new [] {"Cricket", "Chess"})) Output:


<select id="ListBox1" multiple="multiple" name="ListBox1"> <option>Cricket</option>
<option>Chess</option> </select>

Introduction:

My this article on Interview Questions and Answers of MVC basically covers most of the MVC 2, MVC3
and MVC4 topics that are more likely to be asked in job interviews/tests/exams.

The sole purpose of this article is to sum up important questions and answers that can be used by
developers to brush-up all about MVC before they take any interview of the same kind.

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 { get; set; } // Employee's unique identifier

public string FirstName { get; set; } // Employee's first name

public string LastName { get; set; } // Employee's last name


public DateTime DateCreated { get; set; } // 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 { get; set; }

public string LastName { get; set; }

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.FirstName, new { maxlength = "50", size = "50"})

@Html.ValidationMessageFor(x => x.FirstName)

</td>

</tr>

<tr>

<td><b>Last Name:</b></td>

<td>@Html.TextBoxFor(x => x.LastName, new { 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(1, 50)

.WithMessage("First name must not be greater than 50 characters");

RuleFor(x => x.LastName)

.NotEmpty()

.WithMessage("Last name required")

.Length(1, 50)

.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().

What is ASP.NET?
ASP.NET is a framework for building web pages and web sites with HTML, CSS, JavaScript and server
scripting. It follows object oriented programming approach. It is not a programming language. If we write
code in note pad and run it we will get output. It is a server side technology. It uses all .NET compatible
language such as C#, VB.NET, J# etc. If we write our code in any language after compilation .NET
convert it into MSIL.

What are the Development Models in ASP.NET?

ASP.NET supports three different development models. Such:

1. Web Pages- It is a Simplest ASP.NET model. It is Similar to PHP and classic ASP.

2. MVC (Model View Controller)- MVC separates web applications into 3 different components:
Models for data,Views for display,Controllers for input.

3. Web Forms -The traditional ASP.NET event driven development model.

What is MVC (Model View Controller)?

The is MVC (Model View Controller) is a design pattern used in software engineering. These patterns
propose there components or object to be used in software development:

o Models – data access layer. This can be direct data access, web services, etc

o Views – presentation layer of the application. This the users interface.

o Controllers – business logic for the application. It controls Models & View.

What is ASP.NET MVC?

ASP.NET MVC is a web development framework developed by Microsoft Corporation. It is based on


MVC (Model-View-Controller) architectural design pattern.

History of MVC

For the first time MVC Architecture was implemented by Trygve Reenskaug at 1979. It was implemented
on Smalltalk at Xerox labs. The coders and software engineers accept the benefits and advantages of this
architecture.

Difference between ASP.NET WebForms and ASP.NET MVC?

ASP.NET WebForms

1. It uses Page controller pattern approach for rendering layout. That means every page has its own
controller (code-behind page)

2. Page size is big. Because it has large viewstate

3. Testing is difficult.

4. It is good for small scale of application and limited team size.


ASP.NET MVC

1. It uses Front Controller approach. That means a common controller for all pages.

2. Page size is small. Because, it has no viewstate.

3. Testing is easy.

4. It is good for large scale of application with large team size.

Is MVC different from a three layered architecture?

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

Look and Feel- [Three layered architecture] User interface [MVC] View

UI logic- [Three layered architecture] User interface [MVC] Controller

Business logic /validations- [Three layered architecture] Middle layer [MVC] Model

Request is first sent to- [Three layered architecture] User interface [MVC] Controller

Accessing data- [Three layered architecture] Data access layer [MVC] Model

What are the Core features of ASP.NET MVC?

Clear separation of application Presentation and Business Logic layer

An extensible and pluggable framework

Extensive support for ASP.NET Routing

Support for existing ASP.NET features

Explain the complete flow of MVC?

All clients or end user requests are first sent to the controller. Depending on the request the controller
decides which model will use to fulfill the request. The controllers load the model and generate the
appropriate view. The final view is sent to the end user on the browser.

Is MVC suitable for both Windows and Web applications?

The MVC architecture is suitable for a web application than Windows. For Window applications MVP
(Model View Presenter) is more appropriate. If you are using WPF and Silverlight then MVVM is more
suitable due to bindings.

What are the benefits of using MVC?

By using MVC we can get some benefits:


Separation of layer. If we write our code in a class file instead of code-behind page we can reuse the same
code.

Page size is small. Because, it has no viewstate.

Testing is easy. Automated UI testing is possible.

How can we do authentication and authorization in MVC?

We can use Windows or Forms authentication for MVC.

What is Razor in MVC?

Razor is a light weight view engine. Before MVC 3 there was only one view type (ASPX). Razor was
introduced in MVC 3.

Why Razor when we already have ASPX?

Razor is clean, lightweight, and syntaxes are easy as compared to ASPX.

For example in ASPX to display time we need to write:

<%=DateTime.Now%>

But in Razor the code is simple:

@DateTime.Now

So which is a better fit, Razor or ASPX?

As per Microsoft, Razor is more preferred. Because it’s light weight and has simple syntaxes.

How to implement AJAX in MVC?

We can implement AJAX in MVC in two ways:

o AJAX libraries

o jQuery

What is Routing in ASP.NET MVC?

In typical ASP.NET application all the incoming requests are mapped to physical files such as .aspx file.
ASP.NET MVC framework uses friendly URLs that are not mapped to physical files. It uses a routing
engine that maps URLs to controller. We can define our routing rules for the engine so that it can map
incoming request URLs to appropriate controller.

In a browser for an ASP.NET MVC application when a user type a URL and presses “go” button, routing
engine uses routing rules that are defined in Global.asax file and find out the path of corresponding
controller.
Can we create our custom view engine using MVC?

Yes.

Where is the route mapping code written?

It is written in the global.asax file.

Can we map multiple URL’s to the same action?

Yes, we can. We just need to make two entries with different key names and specify the same controller
and action.

How can we navigate from one view to another using a hyperlink?

We can do it by using the ActionLink method. Here is a sample code that navigates the “Home”
controller and invokes the GotoHome action.

<%= Html.ActionLink(“Home”,”Gotohome”) %>

What are ViewData, ViewBag and TempData?

ASP.NET MVC provides 3 options (ViewData, VieBag and TempData) for passing data from controller
to view and in next subsequent request. Among them ViewData and ViewBag are almost similar and
TempData performs additional responsibility.

ViewData and ViewBag are used to communicate between controller and corresponding view.

TempData allows for persisting information for the duration of a single subsequent request. TempData is
also a dictionary object. It stays for the time of an HTTP Request. It can be used to maintain data between
redirects (from one controller to the other controller).

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.

Give an example of ViewBag & ViewData

An example of ViewBag and ViewData is given bellow:

public ActionResult Index()

ViewBag.Name = "Monjurul Habib";


return View();

public ActionResult Index()

ViewData["Name"] = "Monjurul Habib";

return View();

In View:

@ViewBag.Name

@ViewData["Name"]

TempData Example

Sample code is given bellow:

public ActionResult Index()

var model = new Review()

Body = "Start",

Rating=5

};

TempData["ModelName"] = model;

return RedirectToAction("About");

public ActionResult About()

{
var model= TempData["ModelName"];

return View(model);

What is the difference between ActionResult and ViewResult?

ActionResult is an abstract class. ViewResult derives from the ActionResult. ActionResult has several
derived classes (ViewResult, JsonResult, FileStreamResult).

ActionResult can be used to exploit polymorphism. So if you want to return different types of views
dynamically then ActionResult is the best thing.

Is MVC appropriate for both Windows and Web applications?

The MVC architecture is suitable for a web application than Windows application. For Window
applications, MVP (Model View Presenter) is more applicable. For using WPF and Silverlight MVVM is
more suitable.

What is the latest version of ASP.Net MVC?

The latest version of ASP.NET MVC is 6.

What is HTML helper in MVC?

The HTML helper helps us to render the HTML controls in the view. The code to display a HTML
textbox on the view is given bellow:

<%= Html.TextBox("StudentName") %>

How a session is maintained in MVC?

We can maintain sessions in MVC by three ways: tempdata, viewdata, and viewbag.

What is the difference between TempData and ViewData ?

TempData maintains data for the complete request while ViewData maintains data only from Controller
to the view.

Does the value of TempData is available in the next request also?

The value of TempData is available in the current request and in the subsequent request. But it is depends
on whether it is read or not. If it is read one time then, it will not be available in the subsequent request.

What is a partial view in MVC?

In MVC, the partial view is like a user control, a reusable view which can be used inside the other views.
For example let’s say a site have a structure with right menu, header, and footer. Every page will reuse
the left menu, header, and footer sections. For this condition we can create partial views for each of these
sections and then call that partial view in the main view.

How we can create a partial view and use it?

During view adding time, we can create a partial view by checking the “Create partial view” check box.

After the creation we can then call the partial view in the main view using the “Html.RenderPartial”
method. Sample codes for that is shown below:

<body>

<div>

<% Html.RenderPartial(“MyPartialView”); %>

</div>

</body>

How can we use validations in MVC?

In MVC the simplest way for validations is data annotations which can be applied on model properties.
For example, in the below code we have a simple Customer class with a property “CustomerName”.

Here the”CustomerName” property is tagged with a Required data annotation attribute.

public class Customer

[Required(ErrorMessage = "Customer name is required")]

public string CustomerName { set; get; }

In Html helper class, In order to display the validation error message we need to use the
ValidateMessageFor. A sample code is given bellow:

<%=Html.TextBoxFor(m => m.CustomerName)%>

<%=Html.ValidationMessageFor(m => m.CustomerName)%>

Can we display all errors in one place?

Yes, we can. For that we need to use the ValidationSummary method from the Html helper class.

In MVC how can we enable data annotation validation on client side?

We can do that by following two steps.


First step: add the reference of necessary jQuery files.

<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>

<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>

<script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>"


type="text/javascript"></script>

Second step:call the EnableClientValidation method.

<% Html.EnableClientValidation(); %>

What are the different types of action results in MVC?

In MVC there are 12 results. Among them ActionResult class is a base class for all action results. The 11
sub classes are given bellow:

o ViewResult – renders a view as a web page to the response stream

o PartialViewResult – renders a view inside another view

o EmptyResult – returns a empty or null result

o RedirectResult – redirect to another action method (HTTP redirection)

o RedirectToRouteResult – redirect to another action method (HTTP redirection) that is determined


by the routing engine, based on a given route

o JsonResult – returns a JSON object form a ViewData

o JavaScriptResult – returns a script code that can be executed on the client

o ContentResult – returns a user-defined content type

o FileContentResult – returns a file to the client

o FileStreamResult – returns a file to the client, which is supplied by a Stream

o FilePathResult – returns a file to the client

How to implement Windows authentication in MVC?

For Windows authentication, at first we need to change the web.config file and set the authentication
mode to Windows. A sample code for that is given bellow:

<authentication mode="Windows"/>

<authorization>
<deny users="?"/>

</authorization>

Then in the controller or on the action, we can use the Authorize attribute which specifies which users
have access to these controllers and actions. A sample code for that is given bellow, where only the user
“Administrator” can access it.

[Authorize(Users= @”WIN-3LI600MWLQN\Administrator”)]

public class StartController : Controller

//

// GET: /Start/

[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]

public ActionResult Index()

return View("MyView");

How to implement Forms authentication in MVC?

For Windows authentication, at first we need to change the web.config file and set the authentication
mode to Forms. Here the login URL points to a controller rather than a page. A sample code for that is
given bellow:

<authentication mode="Forms">

<forms loginUrl="~/Home/SignIn" timeout="2660"/>

</authentication>

Also we need to create a controller where we will check if the user is valid or not. If the user is valid we
will set the cookie value. A sample C# code for that is given bellow:

public ActionResult SignIn()

if ((Request.Form["txtUserName"] == "MyUserName") &&


(Request.Form["txtPassword"] == "MyPassword"))

FormsAuthentication.SetAuthCookie("MyUserName ", true);

return View("About");

else

return View("Index");

We need to use Authorize attribute so that any unauthorized user can’t call to these controllers. Sample
C# code is given bellow:

[Authorize]

Public ActionResult Default()

return View();

[Authorize]

public ActionResult About()

return View();

What do you know about bundling and minification in MVC?

In MVC, bundling and minification helps us improve request load times of a page. It increases the
performance of the applications.

What is bundling and how to implement bundling in MVC?


In a project we need to use CSS and script files. Bundling helps us to combine multiple JavaScript and
CSS files into a single file. Thus it minimizes the multiple requests in to a single request.

In order to implement bundling open the BundleConfig.cs file from the App_Start folder. Write the
following codes which will combine all the JS files of Scripts folder into a single unit.

What is minification and how to implement minification in MVC?

Minification is a process to remove the blank space, comments etc.

The implementation of minification is as like as bundling. That means when we implement bundling
minification is also implemented automatically. A sample JavaScript codes with comments:

// This is test comments

var x = 5;

x = x + 2;

x = x * 3;

After implementing minification the JavaScript code looks like:

var x=5;x=x+12x=x*3

What is an area in MVC?

In MVC, areas help us to organize all the functionalities into independent modules. For a big project
which has 100’s of controller classes, it is really difficult to manage them. Areas help us to groups all the
classes based on their functionality.

How to implement area in MVC

We can add area by right clicking on the solution and clicking on “Area”. Give an appropriate name for
the area. On the solution explorer we will find Controllers, Models, and Views.

How can you handle multiple Submit buttons in MVC?

Consider we have two submit buttons.

We can handle this problem in two ways. First one is normal HTML way and second one is Ajax way.

For HTML way, we need to create two forms and place the submit button inside each of the forms.
Sample code is given bellow:

<form action="Action1" method=post>

<input type="submit" name="Submit1"/>

</form>
<form action="Action2" method=post>

<input type="submit" name="Submit2">

</form>

In Ajax way, we can create two different functions (“Fun1” and “Fun1”). We need to bundle each of two
functions on button click event. Sample code is given bellow:

<Script language="javascript">

function Fun1()

$.post("/Action1",null,CallBack1);

function Fun2()

$.post("/Action2",null,CallBack2);

</Script>

<form action="/Action1" method=post>

<input type=submit name=sub1 onclick="Fun1()"/>

</form>

<form action="/Action2" method=post>

<input type=submit name=sub2 onclick="Fun2()"/>

</form>

What is Scaffolding in MVC?

Scaffolding is a technique in which MVC template helps us to generate codes for CRUD operations.
During controller creations we need to select

…Controller with read/write actions

…Controller with views, using Entity Framework

In MVC what does scaffolding use internally to connect to database?


Scaffolding uses Entity Framework internally to connect to database.

What is a model binder in MVC?

In MVC, model binder acts like a bridge between HTML UI and MVC model. Sometimes the name of
HTML UI is different than the model property names. For that case we can write the mapping logic in the
binder between the UI and the model.

How can we use multiple models in a single view?

When we bind a model with a view we can select only one model. But if we need to use multiple models
classes in single views, we need to create a new model class which aggregates all the models.

Why we need display mode in MVC?

Display Modes is newly feature added in ASP.NET MVC 4. It helps us to change the view automatically
depending on the user devices (desktop, smart phone, etc).

Is MVC 4 support Windows Azure SDK?

Yes, it supports.

Which namespace is required for MVC?

System.Web.Mvc assembly

In MVC (Model, View & Controller) which one is best to create first?

It is best to create Model.

Can we create automatically generate the codes for CRUD operations?

Yes, if we define Model first we can generate actions automatically.

What are the helper classes?

Instead of writing Input tag you take help of Helper classes. For your understanding these are alike
ASP.NET Server controls. However these have there are lot differences between ASP.NET webforms
server controls like Textbox, Dropdown etc..

Can we access Model in cshtml page?

Yes, we can access Models in cshtml Page or views.

Can we share a view across multiple controllers?

Yes, if we put a view into the shared folder.

How to avoid XSS vulnerabilities in MVC?


To avoid XSS vulnerabilities we need to use the syntax ‘<%: %>’ instead of syntax ‘<%= %>’. It is
applicable in .Net Framework 4.0. It does the HTML encoding. A sample code is given bellow:

<input type="text" value= "<%: value %>"/>

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.

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 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.

Is the following route definition a valid route definition?

{controller}{action}/{id}

No, the above definition is not a valid route definition, because there is no literal value or delimiter
between the placeholders. Therefore, routing cannot determine where to separate the value for the
controller placeholder from the value for the action placeholder.

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
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
canhave11subtypes’sas 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.
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.

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.

--------------------------------------------------------------------------------------

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.

Where are the routing rules defined in an asp.net MVC application?

In Application_Start event in Global.asax

What is the ‘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

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.

Give an example for Authorization filters in an asp.net mvc application?


1. RequireHttps Attribute

2. Authorize Attribute

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

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.

To Read More about Complex Type Click @ me

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 Engine

It’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.

What is ASP.Net MVC?

ASP.NET MVC is a framework for developing web applications in .Net using MVC (Model -View-
Controller) design. MVC is architectural design in which an application is divided among separate
components (Model, view and controller) and each component is responsible for the different task.

• Model - Represent the state and behaviour of data

• View - Display user interface to the end user and display data
• Controller - Responsible for handling user request, processing the request and providing the
response.

Can we use MVC for desktop application?

No, we can not use MVC design pattern for desktop applications. MVC pattern can be used for web
application. We can use MVVM (Model - view - viewModel) and MVP (Model - view - Presenter)
pattern for desktop/ windows applications.

Describe HTML helper in ASP.Net MVC.

HTML helpers are static extension methods defined in InputExtensions class. These helper
methodsrender HTML markup in view. ASP.Net MVC framework provides different inbuilt helper
methods to render different HTML controls.

Below table describes the commonly used HTML helper methods

Name Description

@Html.Label("Name") Display Label

@Html.LabelFor(model=>model.Name)Display model binded label control

@Html.TextBox("textboxName") Display textbox control

@Html.TextBoxFor(model=>model.PropertyName) Display model binded textbox

@Html.TextArea("name") Display Text area

@Html.CheckBox("name") Display checkbox

@Html.CheckBoxFor(model=>model.PropertyName) Display model binded checkbox

@Html.RadioButton("name") Display radio button

@Html.RadioButtonFor(model=>model.PropertyName) Display model binded radio button

@Html.Password("name") Display password field

@Html.PasswordFor(model=>model.PropertyName) Display model binded password field

@Html.Hidden("name") Display hidden field

@Html.HiddenFor(model=>model.PropertyName) Display Model binded hidden field


Explain request flow in ASP.Net MVC.

Below steps explain MVC request flow

• Step 1: User requests any URL/resource.

• Step 2: MVC routing engine parse the URL based on confogured route in routing table

• Step 3: Invoke the matched controller action based on routing configuration.

• Step 4: Controller's action process the user request and return response (response could be
anything. it can be ActionResult or any premitive type string, int, HTTP response).

• Step 5: Before returning response framework check for the return type of response, if retun type
is view result then view engine comes in picture and render specific view.

Can we use the same view across multiple controllers? Explain in detail.

Yes, we can use the same view across multiple controllers.

As we know MVC provides a clear separation of concern. Each component (Model, Controller and view)
have its own responsibilities and works independently.

Controller is responsible for handling and processing the user requests.

Model is responsible for holding data and representing the type of data.

Views are used to display the user interface on the browser.

So we can return any view in response on user request from any controller irrespective of where views are
situated only we need to specify correct path of view so that MVC framework can locate that.

Also, we can pass the same model in different views.

How to improve the performance of page load in asp.net mvc?

ASP.Net MVC provides Minification and Bundling features to improve page load time by reducing the
size of the page and reducing the number of HTTP requests made by the browser to the server in order to
load the page.

System.Web.Optimization assembly is required in order to support bundling and minification.

Explain Bundling and minification.

Bundling and minification provide 2 basic functionality in order to improve the performance of page load.
Bundling - Bundle all the multiple scripts/ CSS files in one file for script bundle and one file for CSS
bundle so that only browser need to load fewer files instead of multiple files.

System.Web.Optimization assembly is required in order to support bundling and minification.

BundleConfig.cs file defines the bundle for scripts and CSS. Below is sample code to create a bundle in
MVC.

1. public class BundleConfig

2. {

3. // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725

4. public static void RegisterBundles(BundleCollection bundles)

5. {

6. //Script bundles

7. bundles.Add(new ScriptBundle("~/bundles/jquery").Include(

8. "~/Scripts/jquery-{version}.js"));

9.

10. bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(

11. "~/Scripts/jquery-ui-{version}.js"));

12.

13. bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(

14. "~/Scripts/jquery.unobtrusive*",

15. "~/Scripts/jquery.validate*"));

16.

17. //Style bundle

18. bundles.Add(new StyleBundle("~/Content/css").Include(

19. "~/Content/site.css",

20. "~/Content/jquery-ui.css"

21. ,"~/Content/SyntaxHighlighter.css"));

22. }
23. }

Minification - Minification process generates a minified file by removing comments, extra white spaces
and renames the variable names. So this reduces the file size and results in the faster download.

How bundling is helpful in improving the performance of page load? Explain.

When a user requests any page then browser loads that page along with all dependent files (scripts, CSS
files, images). In order to load a file browser have to make a new HTTP request. So Browser makes as
many requests as the number of files are attached with the page.

Generally, browsers can make only 6 simultaneous requests to get resources from the server. Additional
requests are queued by the browser for later processing. Hence, if we have multiple files then it may have
towait in the request queue.

Now using bundling, we can combine multiple files in one file, hence reducing the number of files to be
loaded results in faster load time.

What are the area in ASP.Net MVC?

ASP.Net MVC defines areas, helpful in managing a large application into smaller modules. A large
application say, any e-commerce shopping portal may have different sections e.g. Men, Women,
Electronic portal, billing module, reporting and order tracking module, These modules can be managed
into different areas and routing for each area can be managed differently.

Example:

Below application defines 3 areas BillManagement, Order management and Men shopping portal.

An area contains Controllers, Models, Views and AreaRegistration file.

How to define routing for an area in ASP.Net MVC?

Each area in MVC contains <AreaName>AreaRegistration file derived from AreaRegistration base class.
This class had to override RegisterArea method of the base class in order to define the route for that area.

Below code snippet describes, how to define routing for the area?

1. public class BillManagementAreaRegistration : AreaRegistration

2. {

3. public override string AreaName


4. {

5. get

6. {

7. return "Billing";

8. }

9. }

10.

11. public override void RegisterArea(AreaRegistrationContext context)

12. {

13. context.MapRoute(

14. "BillManagement_default",

15. "Billing/{controller}/{action}/{id}",

16. new { action = "Index", id = UrlParameter.Optional }

17. );

18. }

19. }

Now this route will create routing for billing module. Url generated for this area will be looked like
following

http://domainName.com/Billing/{controller}/{action}

What are the filters in ASP.Net MVC?

Filters are the custom classes in ASP.Net MVC that provide functionality to manage the pre-action and
post-action behaviour of the controller action.

If you want to perform any operation after or before any method execution or before result displayed to
the user or on exception then these filters are very useful.

There are 4 types of filters in ASP.Net MVC.

• Authorization filters

• Action Filters
• Result filters

• Exception filters

What is the order in which filters are executed MVC?

Below is the execution order of filters

• Authorization filters - Authorization filter is executed before the execution of any other filters

• Action Filters - Action filters are executed after authorization filter.

• Result filters - Result filter executed after action filter

• Exception filters - Exception filters executes at the last if any exception encountered.

Define authorization filter in MVC.

Authorization filter implements IAuthorizationFilter interface. Authorization filter runs before any other
filter and responsible, to authorize a user request. ASP.Net MVC provides AuthorizeAttribute class to
authorize a request.

Example and Usage:

1. [Authorize]

2. public ActionResult AdminDashBoard()

3. {

4. //To do

5. return View();

6. }

Any request to AdminDashBoard will only be served to the logged in user. If the user is not logged in
then he/she will not be allowed. Authorize attribute can also be used at the controller level. If we define
Authorize attribute at controller level the all the action method inside controller will be accessible for
logged in user.

Describe action filters in MVC?

Action filters implement IActionFilter interface. Action filters execute before and after of an action.
IActionFiler interface provides two methods

• OnActionExcuting - This method runs before excecution of any action

• OnActionExcuted - This method runs after excecution of any action


Action filters are useful in perfroming logging, inspecting return value, canceling execution of the action
method.

Describe exception filters in MVC?

Exception filters implement IExceptionFilter and execute if there is an unhandled exception thrown.
ASP.Net MVC provides HandleErrorAttribute class as an exception filter.

Exception filters can be used for logging or displaying an error page. We may also define our custom
exception filter.

Here is a good post about handling exception in MVC using exception filters.

Question:1

What does MVC represent in ASP.NET?

Answer:

• MVC stands for Model-View-Controller pattern that represents an architectural pattern for
software.

• This separates the components of a Web application and helps in decoupling the business logic.

• It gives more flexibility to overall architecture that allows the changes to be made to a

layer, without affecting the other.

• M represents the Model view that specifies a specific domain data.

• V represents the view of the user interface components used to display the Model data.

• C represents the Controller that handles the user interactions and events. It manipulates the
updates that model reflect at every change of the state of an application.

Question:2

Explain MVC (Model-View-Controller) in general?

Answer:

MVC (Model-View-Controller) is an architectural software pattern that basically decouples various


components of a web application. By using MVC pattern, we can develop applications that are more
flexible to changes without affecting the other components of our application.

• "Model" is basically domain data.


• "View" is user interface to render domain data.

• "Controller" translates user actions into appropriate operations performed on model.

Question:3

What is difference between TempData and ViewData ?

Answer:

“TempData” maintains data for the complete request while “ViewData” maintains data only from
Controller to the view.

Question:4

What is Repository Pattern in ASP.NET MVC?

Answer:

• Repository pattern is used as a default entity operation that allow the decoupling of the
components used for presentation.

• Repository pattern allows easy testing in the form of unit testing and mocking.

• Repository pattern will have the proper infrastructure services to be used in the web applications.

• It uses the mechanism of encapsulating that provides storage, retrieval and query for the
implementation of the repository.

• Repository patterns are hard coded in the application that is to be used in ASP.NET MVC
architecture.

Question:5

What are Action Filters in ASP.NET MVC?

Answer:

If we need to apply some specific logic before or after action methods, we use action filters. We can apply
these action filters to a controller or a specific controller action. Action filters are basically custom classes
that provide a means for adding pre-action or post-action behavior to controller actions.

For example:

• Authorize filter can be used to restrict access to a specific user or a role.

• OutputCache filter can cache the output of a controller action for a specific duration.

Question:6
What kind of logic view model class will have?

Answer:

As the name says view model this class has the gel code or connection code which connects the view and
the model.

So the view model class can have following kind of logics:-

• Color transformation logic: - For example you have a “Grade” property in model and you would
like your UI to display “red” color for high level grade, “yellow” color for low level grade and “green”
color of ok grade.

• Data format transformation logic :-Your model has a property “Status” with “Married” and
“Unmarried” value. In the UI you would like to display it as a checkbox which is checked if “married”
and unchecked if “unmarried”.

• Aggregation logic: -You have two differentCustomer and Address model classes and you have
view which displays both “Customer” and “Address” data on one go.

• Structure downsizing: - You have “Customer” model with “customerCode” and


“CustomerName” and you want to display just “CustomerName”. So you can create a wrapper around
model and expose the necessary properties.

Question:7

What is the difference between ASP.NET MVC and ASP.NET WebForms?

Answer:

• ASP.NET WebForms uses the page controller patterns to render a layout. Whereas, ASP.NET
MVC provides a model that doesn’t have connection with the View so it becomes easier to test and
maintain the applications.

• ASP.NET WebForms uses the Front controller pattern for all the pages to process the web
applications requests and used to facilitate routing architecture. Whereas, ASP.NET MVC has the View
that is called before the controller and this controller is used to render the View that is based on the
actions as the user interacts with the interface.

• ASP.NET WebForms manage the state of the model by using the view state and server based
controls. Whereas, ASP.NET MVC doesn’t manage the state information like WebForms.

• ASP.NET WebForms are event driven. Whereas, ASP.NET MVC are test driven.

Question:8

What is ASP.NET MVC?

Answer:
ASP.NET MVC is a web development framework from Microsoft that is based on MVC (Model-View-
Controller) architectural design pattern. Microsoft has streamlined the development of MVC based
applications using ASP.NET MVC framework.

Question:9

Does “TempData” preserve data in the next request also?

Answer:

“TempData” is available through out for the current request and in the subsequent request it’s available
depending on whether “TempData” is read or not.

So if “TempData” is once read it will not be available in the subsequent request.

Question:10

What are the namespace classes used in ASP.NET MVC?

Answer:

ASP.NET MVC uses the namespace classes that as follows:

• System.Web.Mvc namespace: this consists of classes and interfaces that follows MVC pattern to
create web applications. This includes the controllers, libraries, actions, views, models.

• System.Web.Mvc.Ajax namespace: this consists of classes that support the AJAX scripts and
used in the web applications. This also include the AJAX related settings and options.

• System.Web.Mvc.Async namespace: this consists of classes and interfaces that provide


asynchronous actions in the web applications.

• System.Web.Mvc.Html namespace: this consists of classes in the form of helper application and
follows the MVC pattern. This includes the forms, controls, links, views and validations

Question:11

Explain the role of Model in ASP.NET MVC?

Answer:

One of the core features of ASP.NET MVC is that it separates the input and UI logic from business logic.
Role of Model in ASP.NET MVC is to contain all application logic including validation, business and
data access logic except view, i.e., input and controller, i.e., UI logic.

Model is normally responsible for accessing data from some persistent medium like database and
manipulate it.

Question:12
How do we implement minification?

Answer:

When you implement bundling, minification is implemented by itself. In other words the steps to
implement bundling and minification are the same.

Question:13

How is the ASP.NET MVC architecture different from others?

Answer:

• ASP.NET MVC uses a complete Model-View-Controller architecture that combines the


Controller and the View in a way that both meet the dependency of each other.

• The testing of the architecture can be done by instantiating a View and carrying out the unit tests
without running the controllers through the complete cycle.

• The control of MVC on the output is complete and it renders the HTML in a very clean way.

• The architecture provides an orientation towards the standard compliant pages and control over
the behavior of the applications.

• The knowledge of many programming language gets reduced and the model can become more
abstract from lots of details that is provided for the ease of use.

Question:14

What is Routing in ASP.NET MVC?

Answer:

In case of a typical ASP.NET application, incoming requests are mapped to physical files such as .aspx
file. ASP.NET MVC framework uses friendly URLs that more easily describe user’s action but are not
mapped to physical files.

ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can define
routing rules for the engine, so that it can map incoming request URLs to appropriate controller.

Practically, when a user types a URL in a browser window for an ASP.NET MVC application and presses
“go” button, routing engine uses routing rules that are defined in Global.asax file in order to parse the
URL and find out the path of corresponding controller.

Question:15

So which is a better fit, Razor or ASPX?

Answer:

As per Microsoft, Razor is more preferred because it’s light weight and has simple syntaxes.
Question:16

What is the main function of Razor in ASP.NET

Answer:

• Razor is a view engine that allows the static HTML or the content to be started with the server
and then the content is made dynamic by adding the server code to it.

• Razor is designed to make the process of coding flexible and provide standardization.

• Razor also provides an easy way to integrate the server code into the HTML markup with few
keystrokes.

• Razor is used a view engine that is very expressive in writing style. The coding becomes simpler
due to the support libraries.

• Razor supports many local functions with other functionalities that help in block reading and
writing. It also has pre-defined set of functions that can be used to make the coding more easier.

Question:17

What is the difference between ViewData, ViewBag and TempData?

Answer:

In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework
provides different options i.e., ViewData, ViewBag and TempData.

Both ViewBag and ViewData are used to communicate between controller and corresponding view. But
this communication is only for server call, it becomes null if redirect occurs. So, in short, it's a mechanism
to maintain state between controller and corresponding view.

ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). ViewData
being a dictionary object is accessible using strings as keys and also requires typecasting for complex
types. On the other hand, ViewBag doesn't have typecasting and null checks.

TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be
used to maintain data between redirects, i.e., from one controller to the other controller.

Question:18

What is WebAPI?

Answer:
HTTP is the most used protocol. For the past many years, browser was the most preferred client by which
we consumed data exposed over HTTP. But as years passed by, client variety started spreading out. We
had demand to consume data on HTTP from clients like mobile, JavaScript, Windows applications, etc.

For satisfying the broad range of clients REST was the proposed approach. You can read more about
REST from the WCF chapter.

WebAPI is the technology by which you can expose data over HTTP following REST principles.

Question:19

Why it is useful to use MVC instead of WebForms?

Answer:

• MVC allows the user to write less amount of code to build the web applications as lots of
components are integrated to provide the flexibility in the program.

• Lot of data control options is being provided that can be used in ViewState.

• The application tasks are separated into components to make it easier for the programmers to
write the applications but at the same time the amount of the code also increases.

• Main focus remains on the testability and maintainability of the projects that is being carried out
in large projects.

• It is being used for the projects that require rapid application development.

Question:20

How can you do authentication and authorization in MVC?

Answer:

You can use Windows or Forms authentication for MVC.

Question:21

What is the function of new view engine in ASP.NET?

Answer:

• New View Engine is the pluggable modules that is implemented with templates and provide
syntax options.

• New View Engine uses master file templates of ASP.NET Web Forms that became popular and
includes Spark and NHaml.

• New View Engine uses the HTML generation template approach to optimize the complete work
with the Razor engine.
• Razor is used as a helper that includes all the helper methods and programming model features to
synchronize with the .ASPX view engine.

• Multiple views are also popular using a single application or the site as the template can be
viewed using a single engine or more flexibility can be given to the use of template.

Question:22

If we have multiple filters, what’s the sequence for execution?

Answer:

• Authorization filters

• Action filters

• Response filters

• Exception filters

What are the 3 main components of an ASP.NET MVC application?

1. M - Model

2. V - View

3. C - Controller

In which assembly is the MVC framework defined?

System.Web.Mvc

Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?

Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.

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

Model: Model represents the application data domain. In short the applications business logic is contained
with in the model.
View: Views 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: 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 greatest advantage of using asp.net mvc over asp.net webforms?

It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET
Webforms?

ASP.NET MVC

What are the advantages of ASP.NET MVC?

1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.

2. Complex applications can be easily managed

3. Seperation of concerns. Different aspects of the application can be divided into Model, View and
Controller.

4. ASP.NET MVC views are light weight, as they donot use viewstate.

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.

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.
What is the role of a controller in an MVC application?

The controller responds to user interactions, with the application, by selecting the action method to
execute and alse selecting the view to render.

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?

The following are just a few return types of a controller action method. In general an action method can
return an instance of a any class that derives from ActionResult class.

1. ViewResult

2. JavaScriptResult

3. RedirectResult

4. ContentResult

5. JsonResult

What is the significance of NonActionAttribute?

In general, all public methods of a controller class are treated as action methods. If you want prevent this
default behaviour, just decorate the public method with NonActionAttribute.

What is the significance of ASP.NET routing?

ASP.NET MVC uses ASP.NET routing, to map 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.

What are the 3 segments of the default route, that is present in an ASP.NET MVC application?

1st Segment - Controller Name

2nd Segment - Action Method Name


3rd Segment - Parameter that is passed to the action method

Example: http://pragimtech.com/Customer/Details/5

Controller Name = Customer

Action Method Name = Details

Parameter Id = 5

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.

What is the adavantage of using ASP.NET routing?

In an ASP.NET web application that does not make use of routing, an incoming browser request should
map to a physical file. If the file does not exist, we get page not found error.

An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map
to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are
descriptive of the user's action and therefore are more easily understood by users.

What are the 3 things that are needed to specify a route?

1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the
request handler without requiring a query string.

2. Handler - The handler can be a physical file such as an .aspx file or a controller class.

3. Name for the Route - Name is optional.

Is the following route definition a valid route definition?

{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter
between the placeholders. Therefore, routing cannot determine where to separate the value for the
controller placeholder from the value for the action placeholder.

What is the use of the following default route?

{resource}.axd/{*pathInfo}

This route definition, prevent requests for the Web resource files such as WebResource.axd or
ScriptResource.axd from being passed to a controller.

What is the difference between adding routes, to a webforms application and to an mvc application?

To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class,
where as to add routes to an MVC application we use MapRoute() method.

How do you handle variable number of segments in a route definition?

Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all
parameter.

controller/{action}/{*parametervalues}

What are the 2 ways of adding constraints to a route?

1. Use regular expressions

2. Use an object that implements IRouteConstraint interface

Give 2 examples for scenarios when routing is not applied?

1. A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by
setting the RouteExistingFiles property of the RouteCollection object to true.

2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent
routing from handling certain requests.

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

What are the different types of filters, in an asp.net mvc application?

1. Authorization filters

2. Action filters

3. Result filters

4. Exception filters

Give an example for Authorization filters in an asp.net mvc application?

1. RequireHttpsAttribute

2. AuthorizeAttribute

Which filter executes first in an asp.net mvc application?

Authorization filter

What are the levels at which filters can be applied in an asp.net mvc application?

1. Action Method

2. Controller

3. Application
[b]Is it possible to create a custom filter?[/b]

Yes

What filters are executed in the end?

Exception Filters

Is it possible to cancel filter execution?

Yes

What type of filter does OutputCacheAttribute class represents?

Result Filter

What are the 2 popular asp.net mvc view engines?

1. Razor

2. .aspx

What symbol would you use to denote, the start of a code block in razor views?

What symbol would you use to denote, the start of a code block in aspx views?

<%= %>

In razor syntax, what is the escape sequence character for @ symbol?

The escape sequence character for @ symbol, is another @ symbol

When using razor views, do you have to take any special steps to proctect your asp.net mvc application
from cross site scripting (XSS) attacks?
No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site
scripting (XSS) attacks.

When using aspx view engine, to have a consistent look and feel, across all pages of the application, we
can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views?

To have a consistent look and feel when using razor views, we can make use of layout pages. Layout
pages, reside in the shared folder, and are named as _Layout.cshtml

What are sections?

Layout pages, can define sections, which can then be overriden by specific views making use of the
layout. Defining and overriding sections is optional.

What are the file extensions for razor views?

1. .cshtml - If the programming lanugaue is C#

2. .vbhtml - If the programming lanugaue is VB

How do you specify comments using razor syntax?

Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end. An
example is shown below.

@* This is a Comment *@

Advance:

What is MVC?

MVC is a framework methodology that divides an application’s implementation into three component
roles: models, views, and controllers.
“Models” in a MVC based application are the components of the application that are responsible for
maintaining state. Often this state is persisted inside a database (for example: we might have a Product
class that is used to represent order data from the Products table inside SQL).

“Views” in a MVC based application are the components responsible for displaying the application’s user
interface. Typically this UI is created off of the model data (for example: we might create an Product
“Edit” view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product
object).

“Controllers” in a MVC based application are the components responsible for handling end user
interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC
application the view is only about displaying information – it is the controller that handles and responds
to user input and interaction.

What are the 3 main components of an ASP.NET MVC application?

1. M - Model

2. V - View

3. C - Controller

1- In which assembly is the MVC framework defined?

System.Web.Mvc

2- Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?

Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.

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

Model: Model represents the application data domain. In short the applications business logic is contained
with in the model.

View: Views 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: 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.

4- What is the greatest advantage of using asp.net mvc over asp.net webforms?

It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

5- Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET
Webforms?

ASP.NET MVC

6- What is Razor View Engine?

Razor view engine is a new view engine created with ASP.Net MVC model using specially designed
Razor parser to render the HTML out of dynamic server side code. It allows us to write Compact,
Expressive, Clean and Fluid code with new syntaxes to include server side code in to HTML.

7- What are the advantages of ASP.NET MVC?

1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.

2. Complex applications can be easily managed

3. Seperation of concerns. Different aspects of the application can be divided into Model, View and
Controller.

4. ASP.NET MVC views are light weight, as they donot use viewstate.

8- 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.

9- What is namespace of asp.net mvc?


ASP.NET MVC namespaces and classes are located in the System.Web.Mvc assembly.

System.Web.Mvc 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.

System.Web.Mvc.Ajax namespace

Contains classes that support Ajax scripts in an ASP.NET MVC application. The namespace includes
support for Ajax scripts and Ajax option settings.

System.Web.Mvc.Async namespace

Contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application

System.Web.Mvc.Html namespace

Contains classes that help render HTML controls in an MVC application. The namespace includes classes
that support forms, input controls, links, partial views, and validation.

10- 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.

11- What is the role of a controller in an MVC application?

The controller responds to user interactions, with the application, by selecting the action method to
execute and alse selecting the view to render.

12- Where are the routing rules defined in an asp.net MVC application?

In Application_Start event in Global.asax

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

The following are just a few return types of a controller action method. In general an action method can
return an instance of a any class that derives from ActionResult class.

1. ViewResult
2. JavaScriptResult

3. RedirectResult

4. ContentResult

5. JsonResult

14- What is the ‘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

15- What is the significance of NonActionAttribute?

In general, all public methods of a controller class are treated as action methods. If you want prevent this
default behaviour, just decorate the public method with NonActionAttribute.

16- What is the significance of ASP.NET routing?

ASP.NET MVC uses ASP.NET routing, to map 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.

17- 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.

18- What are the 3 segments of the default route, that is present in an ASP.NET MVC application?

1st Segment - Controller Name


2nd Segment - Action Method Name

3rd Segment - Parameter that is passed to the action method

Example: http://google.com/search/label/MVC

Controller Name = search

Action Method Name = label

Parameter Id = MVC

19- 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.

How do you avoid XSS Vulnerabilities in ASP.NET MVC?

Use thesyntax in ASP.NET MVC instead of usingin .net framework 4.0.

20- What is the adavantage of using ASP.NET routing?

In an ASP.NET web application that does not make use of routing, an incoming browser request should
map to a physical file. If the file does not exist, we get page not found error.

An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map
to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are
descriptive of the user's action and therefore are more easily understood by users.

21- What are the 3 things that are needed to specify a route?

1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the
request handler without requiring a query string.

2. Handler - The handler can be a physical file such as an .aspx file or a controller class.

3. Name for the Route - Name is optional.


22- Is the following route definition a valid route definition?

{controller}{action}/{id}

No, the above definition is not a valid route definition, because there is no literal value or delimiter
between the placeholders. Therefore, routing cannot determine where to separate the value for the
controller placeholder from the value for the action placeholder.

23- What is the use of the following default route?

{resource}.axd/{*pathInfo}

This route definition, prevent requests for the Web resource files such as WebResource.axd or
ScriptResource.axd from being passed to a controller.

24- What is the difference between adding routes, to a webforms application and to an mvc application?

To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class,
where as to add routes to an MVC application we use MapRoute() method.

25- How do you handle variable number of segments in a route definition?

Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all
parameter.

controller/{action}/{*parametervalues}

26- What are the 2 ways of adding constraints to a route?

1. Use regular expressions

2. Use an object that implements IRouteConstraint interface

27- Give 2 examples for scenarios when routing is not applied?

1. A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by
setting the RouteExistingFiles property of the RouteCollection object to true.
2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent
routing from handling certain requests.

28- 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.

29- If I have multiple filters implemented, what is the order in which these filters get executed?

1. Authorization filters

2. Action filters

3. Response filters

4. Exception filters

30- What are the different types of filters, in an asp.net mvc application?

1. Authorization filters

2. Action filters

3. Result filters

4. Exception filters

31- Give an example for Authorization filters in an asp.net mvc application?

1. RequireHttpsAttribute

2. AuthorizeAttribute

32- Which filter executes first in an asp.net mvc application?

Authorization filter

33- What are the levels at which filters can be applied in an asp.net mvc application?

1. Action Method
2. Controller

3. Application

34- Is it possible to create a custom filter?

Yes

35- What filters are executed in the end?

Exception Filters

36- Is it possible to cancel filter execution?

Yes

37- What type of filter does OutputCacheAttribute class represents?

Result Filter

38- What are the 2 popular asp.net mvc view engines?

1. Razor

2. .aspx

39- 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.

40- What symbol would you use to denote, the start of a code block in razor views?

@
41- What symbol would you use to denote, the start of a code block in aspx views?

<%= %>

In razor syntax, what is the escape sequence character for @ symbol?

The escape sequence character for @ symbol, is another @ symbol

42- When using razor views, do you have to take any special steps to proctect your asp.net mvc
application from cross site scripting (XSS) attacks?

No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site
scripting (XSS) attacks.

43- When using aspx view engine, to have a consistent look and feel, across all pages of the application,
we can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor
views?

To have a consistent look and feel when using razor views, we can make use of layout pages. Layout
pages, reside in the shared folder, and are named as _Layout.cshtml

44- What are sections?

Layout pages, can define sections, which can then be overriden by specific views making use of the
layout. Defining and overriding sections is optional.

45- What are the file extensions for razor views?

1. .cshtml - If the programming lanugaue is C#

2. .vbhtml - If the programming lanugaue is VB

46- How do you specify comments using razor syntax?

Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end.

47- What is Routing?


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.

1.What Is MVC?

MVC is new Microsoft framework which used to develop interactive web applications.It is a design
pattern of Model,View ,Controller. View is responsible for designing user interface.Model is Responsible
for binding and retrieving data.Controller is handling interactions between views and Models.

2.What is the latest MVC framework?

The Latest MVC framework is MVC 5.2.0. This framework is available with visual Studio 2013. Since
the earlier mvc frameworks are MVC 4.0,3.0

3.What is the Default Namespace used in MVC Framework?

The Default Namespace in MVC Framework is using System.Web.Mvc;

4.What is Routing in MVC?

Routing is used to configure the default route values of mvc Application.Which means that we can
configure which controller ,which action method should execute when we launch the application at initial
start up.For better understanding in Asp.net if we want launch any web page at first we set the property of
"set as Start page". At the same in Mvc we need to use Routing concept for setting default action method.

Namespace for Routing : using System.Web.Routing;

5.What is the URL Structure of MVC?

The MVC URL Structure is {Your server name/controller name / Action Method name/ Parameters
(optional) }

Example : http://localhost/Home/Create

6.What is the difference between views and Model?

Views are implemented for user interface which holds user input elements and models are holds data for
manipulation.

7.How many models a view can have?

A view can have only one Model.

8.Can we use single model into multiple views?

Yes we can use single model into multiple views.

9.Difference between ViewBag and ViewData?


ViewData is a Dictionary Object which accessible using strings as keys.Ex ViewData[“username”]
="Test" and its requires type casting for Complex dataType.

ViewBag is dynamic property and it does not require type casting for complex Data Type. Ex
ViewBag.username ="Text"

We can access above two properties in view as below

@ViewBag.username

@ViewData[“username”]

10.What are Engines available in mvc?

In MVC two view engines are available.First one is Razor view Engine and Second one is Aspx View
Engine.

11.What is Partial view?

Partial view is a view which can contain user controls same as normal view.We can reuse the partial view
as many times we want in required places.For example a application requires more than three registration
forms So we need to create three separate view for doing this .Instead of we can create a single view and
we can use this view into all the places.

12.How to add model in view?

We can add model object using the following syntax

@model Projectname.Model Class Namespace

Example : @model SampleProject.Models.Register

13.What is the Advantage of MVC?

MVC has many advantages compare to Asp.Net.Since am listing most important features here

Separation of concern – view,model,controller are separated into individual files so it is easy to manage
the complexity of application.

TDD (Test Driven Development) – Which used to unit test the application for repeated source code
changes

Extensible and pluggable -Mvc framework components are easy to flexible and extensible and
customized more than web forms

Asp.Net Features Supported – its supports asp.net features like authentication,roles,membership and etc..

URL Routing – Routing allows to set default entry point of your application

14.What is the use of Html.BeginForm()


Html.BeginForm() is render the form that will handled by Controller Action method for further
manipulation.In order words if you want post your data to your controller from view you should use this
method in order to submit the data.

15.What is the use of AntiForgeryToken() in MVC?

AntiForgeryToken is used to protect you application against cross-site request forgery.To use this method
you need to include AntiForgeryToken into form element and include
ValidateAntiForgeryTokenAttribute into Controller Action Method.

Ex : In view Page use @Html.AntiForgeryToken();

In Controller page add this into Above of ActionMethod[ValidateAntiForgeryToken]

16.What is the namespace to avoid AntiForgeryToken in Mvc?

System.Web.Mvc -this namespace is used for avoiding Cross site Forgery

17.What is the use of RenderBody Property in MVC?

RenderBody method which is used to render the pages when you use common Layout page in your
application.If you not declaring @RenderBody() method in your common layout page then it will throw
error to include this method in your layout page.For more understanding RenderBody is equivalent to
ContentPlaceHolder in Asp.net.

18.Where we need to Declare RenderBody() Method?

We need to Declare @RenderBody() method in our master or Layout page.Reminder that other pages
should inherit the master or layout page.

19.What is the equivalent of master page in MVC?

In MVC layout page is equivalent of master page in asp.net.For creating common header,menus you can
use layout page in mvc.

Questions Which may be asked in ASP.Net MVC Interview.

1- what is ASP.Net MVC?

2- What is Razor?

3- What is TDD?

4- What is BDD?

5- What is Dependency Injection (DI)?

6- What is ViewData and ViewBag?


7- In which assembly is the MVC framework defined?

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

9- What are the advantages of ASP.NET MVC?

10- Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET
Webforms?

11- Name of different return types of a controller action method?

12- What is the significance of NonActionAttribute?

13- Is it possible to share a view across multiple controllers?

14- What is the role of a controller in an MVC application?

15- Where are the routing rules defined in an asp.net MVC application?

16- What are the 3 segments of the default route, that is present in an ASP.NET MVC application?

17- ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are
these 2 places?

18- What is the adavantage of using ASP.NET routing?

19- What are the 3 things that are needed to specify a route?

20- What is the use of the following default route?

21- What is the difference between adding routes, to a webforms application and to an mvc application?

22- How do you handle variable number of segments in a route definition?

23- What are the 2 ways of adding constraints to a route?

24- Give 2 examples for scenarios when routing is not applied?

25- What is the use of action filters in an MVC application?

26- If I have multiple filters impleted, what is the order in which these filters get executed?

27- What are the different types of filters, in an asp.net mvc application?

28-Give an example for Authorization filters in an asp.net mvc application?

29- Which filter executes first in an asp.net mvc application?

30- What are the levels at which filters can be applied in an asp.net mvc application?

31- Is it possible to create a custom filter?


32- What filters are executed in the end?

33- Is it possible to cancel filter execution?

34- What type of filter does OutputCacheAttribute class represents?

35- What are the 2 popular asp.net mvc view engines? 36- What symbol would you use to denote, the
start of a code block in razor views?

37-What symbol would you use to denote, the start of a code block in aspx views?

38- In razor syntax, what is the escape sequence character for @ symbol?

39- When using razor views, do you have to take any special steps to proctect your asp.net mvc
application from cross site scripting (XSS) attacks?

40- What is asp.net master pages equivalent, when using razor views?

41- What are sections?

42- What are the file extensions for razor views?

43- How do you specify comments using razor syntax?

44-What's the deal with values parameter in ASP.NET MVC?

45- What website hosting is good for ASP.NET MVC?

46- What is Area in Asp.Net MVC projects and how to implement area in ASP.Net Projects/

47- How to Use Session in ASP.Net mVC Projects?

48- How to persist data from one page to another page in ASP.Net application?

49- What is Tempdata?

50- What is JSON?

51-What is Lambda Expression?

1. What is difference between Asp.net and Asp.net MVC?

2. If on a page i have button, i want to execute some logic on click event, how will i do this in Asp.net
MVC?

3. Why to use MVC over ASP.net website?

4. What kind of relationship is between View and controller?

5. MVC and ASP.net application pipeline difference?

6. What is ActionResult?
7. What are types of Views?

8. Request lifecycle Scenario(MVC) : If you have a partial view and want to update the tab on the layout
view how do you do that ?

9. MVC life cycle?

10. Architecture of last project, MVP pattern?

11. What is difference between MVC and MVP?

12. What is the url we get if application is in MVC?

13. Partial views on MVC? ?

14. HTML helper class of MVC?

15. MVC lifecycle?

16. Post – Redirect – Get Design Pattern?

17. Registration design pattern?

18. Bootstrapper design pattern?

19. Strongly typed views?

20. Difference between viewbag, viewdata, tempdata, session?

21. Abount Scaffolding?

22. About ActionFilters?

23. What is MVVM pattern.

24. MVVM vs MVC?

25. explain how to develop MVC application in detail? How to maintain caching at each level? Features
of MVC3.0

26. How to improve performance of a normal Html Page in ASP.NET ( No Code Behinds ) as well as
MVC

27. What Html element you will use to add two columns in your page

28. What is the difference between render partial and render action

29. How will you restrict user to access a specific controller action(ans: using filter)

30. Advantages of MVC or ASP.Net

31. Security aspect of MVC application and some scenario based questions for [Authoriza] attributes
32. What is ExtJS? 3. What is Container? 4. Explain EXT MVC architecture

33. How to return Json from controller Action?

34. How to return XML from Controller Action?

You might also like