Explain MVC (Model-View-Controller) in General?
Explain MVC (Model-View-Controller) in General?
Explain MVC (Model-View-Controller) in General?
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.
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?
5. Can you please explain the request flow in ASP.NET MVC framework?
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.
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.
http://locahost:XXXX/Student.aspx
//Displaying a student by Id = 5
http://locahost:XXXX/Student.aspx?Id=5
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.
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.
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
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]
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.
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,
OutputCache filter can cache the output of a controller action for a specific duration.
and more…
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
Comprehensive ASP.NET MVC [3D BUZZ] 34 lectures, 14 Hours Video, All Levels
ASP.NET Identity
Authentication Filters
Filter Overrides
Scaffolding
Bootstrap
Attribute Routing
“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.
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:
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
There are multiple scenarios where using ViewModel becomes obvious choice. For example:
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:
and
@Html.TextBox(“strEmployeeName”) renders:
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.
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.
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.
Forms Authentication
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.
• 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.
• Mobile templates
• Added ASP.NET Web API template for creating REST based services.
• Segregating the configs for MVC routing, Web API, Bundle etc.
• App initialization
• Routing
• Improved reusability of model and views. We can have multiple views which can point to the
same model and vice versa.
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.
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
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.
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.
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.
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.
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 –
Just add the method – “MapMvcAttributeRoutes()” to enable attribute routing as shown below
routes.IgnoareRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//convention-based routing
routes.MapRoute
name: "Default",
url: "{controller}/{action}/{id}",
);
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.
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.
"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.
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.
System.Web.Mvc
System.Web.Mvc.Ajax
System.Web.Mvc.Html
System.Web.Mvc.Async
ViewBag is a wrapper around ViewData, which allows to create dynamic properties. Advantage of
viewbag over viewdata will be –
• 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.
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.
• 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.
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.
• 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.
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.
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")
@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 –
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.
Below are the methods used to render the views from action -
• RedirectToRoute() – Redirect to action from the specified URL but URL in the route table has
been matched.
ActionResult is used to represent the action method result. Below are the subtypes of ActionResult –
• ViewResult
• PartialViewResult
• RedirectToRouteResult
• RedirectResult
• JavascriptResult
• JSONResult
• FileResult
• HTTPStatusCodeResult
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]
{
// Method logic
“ActionName” attribute can be used for changing the action name. Below is the sample code snippet to
demonstrate more –
[ActionName("TestActionNew")]
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.
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";
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?
<script type="text/javascript">
function DrpIndexChanged() { }
</script>
Invoke the method:
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")
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"); }
"RouteConfig.cs" holds the routing configuration for MVC. RouteConfig will be initialized on
Application_Start event registered in Global.asax.
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.
• 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.
• 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.
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?
Below are the two types of extensions razor view can have –
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()
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.
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.
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?
• Authentication
• Authorization
• HandleError
• OutputCache
53) How can we determine action invoked from HTTP GET or HTTP POST?
• 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
}
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”.
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.
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.
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”);
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.
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.
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 –
AreaRegistration.RegisterAllAreas();
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.
“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]
//Logic here
return PartialView();
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.
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.
• NUnit
• xUnit.NET
• Ninject 2
• Moq
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.
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.
$('#CustomerName').rules("add", {
required: true,
minlength: 2,
messages: {
});
Below is the scenario and the solution to solve multiple submit buttons issue.
Scenario –
@using (Html.BeginForm(“MyTestAction”,”MyTestController”)
Solution :
Public ActionResult MyTestAction(string submit) //submit will have value either “MySave” or “MyEdit”
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.
<script type="text/javascript">
<text>
</text>
</script>
[ActionName("NewActionName")]
return View();
A) System.Web.HttpContext.Current.Session["LoginID"] =7;
B) Current.Session["LoginID"] =7;
C) Session["LoginID"] =7;
D) None
A) 304
B) 302
C) 301
D) 300
E) None
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
A) Server.Transfer()
B) Response.Redirect()
C) Both A and B
D) None
A) DataSet
B) Datatable
C) A and B
D) None
A) Yes
B) No
C) Both A & B
D) None
A) Top-Down
B) Down-Up
C) Pipeline
D) Water fall
C) both a and b
D) None
A) Standard User
B) Administrator
C) Anonymous
D) None
A) cshtml
B) vbhtml
C) None
D) Both A & B
A) cshtml
B) vbhtml
C) None
D) Both A & B
A) *@ Comment me *@
B) @* Comment me *@
C) @* Comment me @*
D) *@ Comment me @*
E) None
A) System.Web.Razor
B) System.Web.Mvc.WebFormViewEngine
C) Both A & B
D) None
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.
C) Both A & B
D) None
A) Yes
B) No
C) None
A) Yes
B) No
C) None
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?
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
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.
D) A, B and C.
E) None
Viewstart Code Snippet
@{
Layout = "~/Views/Shared/_Layout.cshtml";
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
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.
Answer: Scaffolding helps us to write CRUD operations blend using Entity Framework, It helps
developer to write down simply even yet complex business logic.
Step 2: Fetch Route: It will gether information about controller and action to invoke.
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
A) System.ComponentModel
B) System.ComponentModel.DataAnnotations
C) Both A and B
D) None
A) System.ComponentModel
B) System.ComponentModel.DataAnnotations
C) Both A and B
D) None
C) Both A) & B)
D) None
A) Yes
B) No
C) Both A) & B)
D) None
B) No
C) Both A) & B)
D) None
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
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
C) None
D) All
56. What is BundleConfig.cs in ASP.Net MVC ?
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
C) None
D) All
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?
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?
C) None
D) Both A and B
Syntax
@Html.Partial("_viewname");
62. How to check Request coming from which controller using MVC ASP.Net?
B) var _controller =
HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
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
D) All
D) None
67. How can we give Title to MVC Charts?
D) All
D) None
A) .NewSeries(chartType: "Bar")
B) .Series(chartType: "Bar")
C) .AddSeries(chartType: "Bar")
D) All
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
73. If Razor View Engine need to add JQuery function and contain @ special character then how we can
write it in Razor View?
B) Replace @ to @@ (double)
C) None
D) Both (A & B)
74. How to set Default Value to Hidden Input Box using ASP.Net MVC?
D) None
D) None
A) App_Data
B) App_Start
C) Content
D) Filters
A) App_Data
B) App_Start
C) Content
D) Filters
A) App_Data
B) App_Start
C) Content
D) Filters
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
A) Action filters
B) Authorization filters
C) Response filters
D) Exception filters
B) Authorization filters
C) Exception filters
D) Response filters
MVC is a software architecture pattern for developing web application. It is handled by three objects
Model-View-Controller.
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
• 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.
• 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
• 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
• 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
Advantages Disadvantages
• All classes and object are independent of each other • The model pattern is little
complex
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?
• Performs routing
• 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.
• ControllerName
• ActionMethodName
• Parameter
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.
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
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.
• Ajax libraries
• Jquery
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 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
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
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.
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?
• Authorization filters
• Action filters
• Response filters
• Exception filters
28) Mention what are the file extensions for razor views?
29) Mention what are the two ways for adding constraints to a route?
• 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.
Ans.
Easy Mobile web applications (ASP.NET MVC 4 complete focus on Mobile application
development)
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.
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.
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.
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.
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.
Ans. Yes, MVC 4 is supporting Windows Azure SDK version 1.6 or higher.
1. M - Model
2. V - View
3. C - Controller
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.
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
1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
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.
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.
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
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.
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?
Example: http://pragimtech.com/Customer/Details/5
Parameter Id = 5
ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are
these 2 places?
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax
file.
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.
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.
{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.
{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.
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all
parameter.
controller/{action}/{*parametervalues}
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.
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
1. Authorization filters
2. Action filters
3. Result filters
4. Exception filters
1. RequireHttpsAttribute
2. AuthorizeAttribute
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
Exception Filters
Yes
Result Filter
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?
<%= %>
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
Layout pages, can define sections, which can then be overriden by specific views making use of the
layout. Defining and overriding sections is optional.
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 *@
Answer: Model-View-Controller.
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
2. {
3. ViewEngines.Engines.Clear();
4. }
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.
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.
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
Answer: Yes, it is possible to share a view across multiple controllers by putting a view into the shared
folder.
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, 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")]
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.
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?
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);
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
);
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
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
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.
• 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.
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
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
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 .
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.
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.
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.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult
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
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
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.
MVC 4 features having two category MVC Framework and mvc project template
MVC 4 Framework
8)Database migration
OData Improvements in MVC 5(Full support for $select, $expand, $batch, and $value)
Attribute routing
Bootstrap In Short:
With the updated MVC template, You can do Customization very easily
routes.MapAttributeRoutes(myConfig =>
myConfig.AddTranslationProvider(new MyCustomTranslationProvider());
});
GetRouteAttributes(MethodInfo actionMethod)
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”)]
[GET(“”)]
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.
Ref :- http://onlinedotnet.com/mvc-5-interview-questions-and-answers/
cook.Expires = DateTime.Now.AddSeconds(1);
Q.What is _ViewSatrt.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
MVC 6
Side by side - deploy the runtime and framework with your application
No need to recompile for every change. Just hit save and refresh the browser.
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
Asp.Net Identity
Authentication Filters
Filter overrides
MVC 4
MVC 3
Razor
MVC 2
Client-Side Validation
Templated Helpers
Areas
Asynchronous Controllers
DataAnnotations Attributes
Model-Validator Providers
Templated Helpers
Ref:- http://www.codeproject.com/Articles/556995/ASP-NET-MVC-interview-questions-with-
answers#WhatisthedifferencebetweeneachversionofMVC2,3,4,5and6
eg:-@Html.TextBox("Name")
Html helpers will help us to create different html controls in the view
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 .
DisplayName – Defines the text we want used on form fields and validation messages
StringLength – Defines a maximum length for a string field
Bind – Lists fields to exclude or include when binding parameter or form values to model properties
[Required]
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength =
6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
[DataType(DataType.Password)]
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.
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.
Views (registering and injecting view engines, injecting dependencies into view pages)
AuthConfig.cs is used to configure security settings, including sites for OAuth login.
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.
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.
RouteConfig.cs holds the granddaddy of the MVC config statements, Route configuration.
Used to register Web API routes, as well as set any additional Web API configuration settings.
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.
The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application
start event.
Yes , you can , you just need to make two entries with different key names and specify the same
controller and action.
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".
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.
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.
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.
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.
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.
• 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.
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.
• 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.
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.
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 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:
• There is one-to-many relationship between Controller and View means one controller can
mapped to multiple views.
• 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.
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.
Here is the list of released version history of ASP.NET MVC Framework with theirs features. ASP.NET
MVC1
• Runs on .NET 3.5 and with Visual Studio 2008 & Visual Studio 2008 SP1
• Html Helpers
• Ajax helpers
• Routing
• Unit Testing
ASP.NET MVC2
• 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
• 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
• Asynchronous controllers
ASP.NET MVC3
• Enhanced Data Annotations attributes for model validation on both client and server sides
• Remote Validation
• Compare Attribute
• Dependency Resolver
• Use of NuGet to deliver software and manage dependencies throughout the platform
ASP.NET MVC4
• Runs on .NET 4.0, 4.5 and with Visual Studio 2010SP1 & Visual Studio 2012
• Display Modes
ASP.NET MVC5
• 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
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.
The main differences between ASP.NET Web Form and ASP.NET MVC are given below:
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.
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.
ViewModel contain fields that are represented in the view (for LabelFor, EditorFor, DisplayFor
helpers)
ViewModel can have multiple entities or objects from different data models or data source.
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.
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.
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.
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.
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.
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.
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
routes.MapRoute(
new
controller = "Home",
action = "Index",
id = UrlParameter.Optional
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.
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.
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")]
return View();
}
//new route: /MyHome/About
return View();
return View();
2. Action level routing – You can define routes at action level which apply to a specific action with in the
controller.
//TO DO:
return View();
return View();
//route: /Home/Contact
return View();
Note :
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.
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")]
//TO DO
</order>
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
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
{
public static void RegisterRoutes(RouteCollection routes)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//convention-based routing
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
UrlParameter.Optional });
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}")]
// route: /admin/menu/login
return View();
}
// route: /admin/menu/products
[Route("products")]
return View();
// route: /categories
[Route("~/categories")]
return View();
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.
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.
routes.MapRoute(
new
controller = "Home",
action = "Index",
id = UrlParameter.Optional
);
routes.MapRoute(
new
controller = "Home",
action = "Index",
id = UrlParameter.Optional
);
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.
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.
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.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.
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.
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.
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:
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 CustomViewEngine()
"~/Views/Shared/{0}.html" };
"~/Views/Shared/{0}.html" };
var physicalpath =
controllerContext.HttpContext.Server.MapPath(partialPath);
var physicalpath =
controllerContext.HttpContext.Server.MapPath(viewPath);
_viewPhysicalPath = ViewPhysicalPath;
//Load File
writer.Write(parsedcontents);
if (m.Success)
if (viewdata.ContainsKey(key))
return viewdata[key].ToString();
return string.Empty;
ViewEngines.Engines.Add(new CustomViewEngine());
Yes, you can remove default view engines (Razor and WebForm) provided by ASP.NET MVC.
ViewEngines.Engines.Clear();
The main differences between ASP.NET Web Form and ASP.NET MVC are given below:
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.
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.
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
{
<ol>
<li>@item</li>
</ol>
<h3>Programming Languages:</h3>
<h3>Book List:</h3>
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:
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?
• 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).
ASP.NET MVC 2 was released in March 2010. Its main features are:
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:
ASP.NET MVC 3 shipped just 10 months after MVC 2 in Jan 2011.Some of the top features in MVC 3
included:
• 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.
• Display Modes.
1. App initialization
2. Routing
3. Improved reusability of views/model. One can have multiple views which can point tosame
model and vice versa.
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.
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
<div class="genre">
<h3><em>@Model.Name</em> Albums</h3>
<ul id="album-list">
<li>
<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.
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.
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.
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.
• Views (registering and injecting view engines, injecting dependencies into view pages)
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:
});
AuthConfig.cs is used to configure security settings, including sites for OAuth login.
system. Several bundles are added by default, including jQuery, jQueryUI, jQuery validation,
Modernizr, and default CSS references.
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.
RouteConfig.cs holds the granddaddy of the MVC config statements, Route configuration.
Used to register Web API routes, as well as set any additional Web API configuration settings.
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.
• Windows XP
• Windows Vista
• Windows 7
• Windows 8
It runs on the following server operating systems:
MVC 4 development tooling is included with Visual Studio 2012 and can be installed on Visual
What are the various types of Application Templates used to create an MVC application?
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
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?
DIRECTORY PURPOSE
/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.
/Content To put CSS and other site content, other than scripts and images
/App_Start To put configuration code for features like Routing, Bundling, Web API.
Note: Some of the content has been taken from various books/articles.
This namespace contains classes and interfaces that support the MVC pattern for ASP.NET Web
applications. This namespace includes classes that represent controllers, controller
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.
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. This namespace includes classes that support forms, input controls, links, partial views, and
validation.
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?
• 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.
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?
For example, you need to assign list of students to the dynamic Students property
of ViewBag.
countries.Add("Akhil");
countries.Add("Ekta");
ViewBag.Students = students;
Note: Some of the content has been taken from various books/articles.
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:
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:
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:
this.employeeService = employeeService;
{
CreateEmployeeViewModel viewModel = new CreateEmployeeViewModel();
return View(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>
</tr>
<tr>
<td><b>Last Name:</b></td>
</td>
</tr>
</table>
Validation would thus be done only on FirstName and LastName. Using Fluent Validation you might
have validation like this:
public CreateEmployeeViewModelValidator()
.NotEmpty()
.Length(1, 50)
.NotEmpty()
.Length(1, 50)
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.
The solution is independed of MVC.NET framework and is global across server side
X-Requested-With = XMLHTTPREQUEST
MVC.NET provides helper function to check for ajax requests which internally inspects
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.
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.
The view also contains links to actions for performing the create/edit/delete
operations.
Razor <span>@model.Message</span>
Code expressions in Razor are always HTML encoded. This Web Forms syntax also automatically
HTML encodes the value.
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
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
<span>Item @item.Name.</span>
Web Forms
<% } %>
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 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?
<script type="text/javascript">
function selectedIndexChanged() {
</script>
onchange="selectedIndexChanged()" })%>
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.
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.
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.
@{
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
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.
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
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!");
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>
</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.
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,
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);
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 ")
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.
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.
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.
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 Controllers – business logic for the application. It controls Models & View.
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.
ASP.NET WebForms
1. It uses Page controller pattern approach for rendering layout. That means every page has its own
controller (code-behind page)
3. Testing is difficult.
1. It uses Front Controller approach. That means a common controller for all pages.
3. Testing is easy.
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
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
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.
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.
Razor is a light weight view engine. Before MVC 3 there was only one view type (ASPX). Razor was
introduced in MVC 3.
<%=DateTime.Now%>
@DateTime.Now
As per Microsoft, Razor is more preferred. Because it’s light weight and has simple syntaxes.
o AJAX libraries
o jQuery
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.
Yes, we can. We just need to make two entries with different key names and specify the same controller
and action.
We can do it by using the ActionLink method. Here is a sample code that navigates the “Home”
controller and invokes the GotoHome action.
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.
return View();
In View:
@ViewBag.Name
@ViewData["Name"]
TempData Example
Body = "Start",
Rating=5
};
TempData["ModelName"] = model;
return RedirectToAction("About");
{
var model= TempData["ModelName"];
return View(model);
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.
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.
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:
We can maintain sessions in MVC by three ways: tempdata, viewdata, and viewbag.
TempData maintains data for the complete request while ViewData maintains data only from Controller
to the view.
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.
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.
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>
</div>
</body>
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”.
In Html helper class, In order to display the validation error message we need to use the
ValidateMessageFor. A sample code is given bellow:
Yes, we can. For that we need to use the ValidationSummary method from the Html helper class.
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:
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”)]
//
// GET: /Start/
[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
return View("MyView");
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">
</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:
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]
return View();
[Authorize]
return View();
In MVC, bundling and minification helps us improve request load times of a page. It increases the
performance of the applications.
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.
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:
var x = 5;
x = x + 2;
x = x * 3;
var x=5;x=x+12x=x*3
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.
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.
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>
<form action="Action2" method=post>
</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>
</form>
Scaffolding is a technique in which MVC template helps us to generate codes for CRUD operations.
During controller creations we need to select
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.
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.
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).
Yes, it supports.
System.Web.Mvc assembly
In MVC (Model, View & Controller) which one is best to create first?
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..
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.
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.
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.
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.
SEO friendly
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.
{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.
5. Display Modes
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.
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>
</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.
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
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.
There 12 kinds of results in MVC, at the top is “ActionResult”class which is a base class that
canhave11subtypes’sas listed below: -
JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
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.
if (1==2)
else
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.TextBoxFor is requires a strongly typed view and uses the view model:
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.
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.
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?
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax
file.
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]
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")]
}
In which assembly is the MVC framework defined?
System.Web.Mvc
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.
1) App initialization
2) Routing
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.
2. Authorize Attribute
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.
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.
RenderPartial writes directly to the response output stream instead of returning a string
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.
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.
*****************************************************************************
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.
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.
LINQ to Entities provides Language-Integrated Query (LINQ) support for querying entities.
When objects are returned by a query, related objects are not loaded at the same time.
Mapping consist information about how your conceptual model is mapped to storage 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.
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.
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.
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
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.
*****************************************************************************
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:
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.
• Getter-Setter Injection : Dependencies are assigned through properties (ex: setter methods).
• 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.
It’s a type of View Engion that is introduced in MVC3 that offers some benefits that like:
3- Razor views can be unit tested without requiring that you run the application or launch a web server.
• @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.
• Support for sharing code among multiple views (_viewstart.cshtml or _viewstart.vbhtml files).
• 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.
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.
• View - Display user interface to the end user and display data
• Controller - Responsible for handling user request, processing the request and providing the
response.
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.
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.
Name Description
• Step 2: MVC routing engine parse the URL based on confogured route in routing table
• 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.
As we know MVC provides a clear separation of concern. Each component (Model, Controller and view)
have its own responsibilities and works independently.
Model is responsible for holding data and representing the type of data.
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.
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.
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.
BundleConfig.cs file defines the bundle for scripts and CSS. Below is sample code to create a bundle in
MVC.
2. {
5. {
6. //Script bundles
7. bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
8. "~/Scripts/jquery-{version}.js"));
9.
11. "~/Scripts/jquery-ui-{version}.js"));
12.
14. "~/Scripts/jquery.unobtrusive*",
15. "~/Scripts/jquery.validate*"));
16.
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.
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.
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.
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?
2. {
5. get
6. {
7. return "Billing";
8. }
9. }
10.
12. {
13. context.MapRoute(
14. "BillManagement_default",
15. "Billing/{controller}/{action}/{id}",
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}
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.
• Authorization filters
• Action Filters
• Result filters
• Exception filters
• Authorization filters - Authorization filter is executed before the execution of any other filters
• Exception filters - Exception filters executes at the last if any exception encountered.
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.
1. [Authorize]
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.
Action filters implement IActionFilter interface. Action filters execute before and after of an action.
IActionFiler interface provides two methods
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
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
• 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
Answer:
Question:3
Answer:
“TempData” maintains data for the complete request while “ViewData” maintains data only from
Controller to the view.
Question:4
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
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:
• 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.
• 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.
Question:7
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
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
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.
Question:10
Answer:
• 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.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
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
Answer:
• 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
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
Answer:
As per Microsoft, Razor is more preferred because it’s light weight and has simple syntaxes.
Question:16
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
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
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
Answer:
Question:21
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
Answer:
• Authorization filters
• Action filters
• Response filters
• Exception filters
1. M - Model
2. V - View
3. C - Controller
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.
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
1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
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.
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.
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
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.
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?
Example: http://pragimtech.com/Customer/Details/5
Parameter Id = 5
ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are
these 2 places?
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax
file.
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.
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.
{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.
{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.
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all
parameter.
controller/{action}/{*parametervalues}
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.
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
1. Authorization filters
2. Action filters
3. Result filters
4. Exception filters
1. RequireHttpsAttribute
2. AuthorizeAttribute
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
Exception Filters
Yes
Result Filter
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?
<%= %>
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
Layout pages, can define sections, which can then be overriden by specific views making use of the
layout. Defining and overriding sections is optional.
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.
1. M - Model
2. V - View
3. C - Controller
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.
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
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.
1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
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.
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.
Yes, put the view into the shared folder. This will automatically make the view available across multiple
controllers.
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?
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
1) App initialization
2) Routing
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.
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.
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?
Example: http://google.com/search/label/MVC
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?
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax
file.
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.
{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.
{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.
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all
parameter.
controller/{action}/{*parametervalues}
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.
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
1. RequireHttpsAttribute
2. AuthorizeAttribute
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
Yes
Exception Filters
Yes
Result Filter
1. Razor
2. .aspx
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?
<%= %>
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
Layout pages, can define sections, which can then be overriden by specific views making use of the
layout. Defining and overriding sections is optional.
Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end.
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.
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
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.
The MVC URL Structure is {Your server name/controller name / Action Method name/ Parameters
(optional) }
Example : http://localhost/Home/Create
Views are implemented for user interface which holds user input elements and models are holds data for
manipulation.
ViewBag is dynamic property and it does not require type casting for complex Data Type. Ex
ViewBag.username ="Text"
@ViewBag.username
@ViewData[“username”]
In MVC two view engines are available.First one is Razor view Engine and Second one is Aspx View
Engine.
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.
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
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.
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.
We need to Declare @RenderBody() method in our master or Layout page.Reminder that other pages
should inherit the master or layout page.
In MVC layout page is equivalent of master page in asp.net.For creating common header,menus you can
use layout page in mvc.
2- What is Razor?
3- What is TDD?
4- What is BDD?
10- Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET
Webforms?
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?
19- What are the 3 things that are needed to specify a route?
21- What is the difference between adding routes, to a webforms application and to 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?
30- What are the levels at which filters can be applied in an asp.net mvc application?
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?
46- What is Area in Asp.Net MVC projects and how to implement area in ASP.Net Projects/
48- How to persist data from one page to another page in ASP.Net application?
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?
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 ?
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)
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