ASP.NET MVC Interview Questions and Answers Book
ASP.NET MVC Interview Questions and Answers Book
All rights reserved. No part of this book can be reproduced or stored in any retrieval system or transmitted in any
form or by any means, electronic, mechanical, photocopying, recording, uploading on server and scanning without
the prior written permission of the Dot Net Tricks Innovation Pvt. Ltd.
The author of this book has tried their best to ensure the accuracy of the information described in this book.
However, the author cannot guarantee the accuracy of the information contained in this book. The author or Dot
Net Tricks Innovation Pvt. Ltd. will not be liable for any damages, incidental or consequential caused directly or
indirectly by this book.
Further, readers should be aware that the websites or reference links listed in this book may have changed or
disappeared between when this book was written and when it is read.
All other trademarks referred to in this book are the property of their respective owners.
Release History
• Initial Release 1.0.0 - 10th Mar 2014
• Second Release 1.0.1 - 1st Jan 2015
• Third Release 1.0.2 - 12th Aug 2016
• Fourth Release 1.1 - 19th Nov 2018
• Fifth Release 1.2 - 4th Jan 2019
1
Page
About Dot Net Tricks
Dot Net Tricks is founded by Shailendra Chauhan (Microsoft MVP), in Jan 2010. Dot Net Tricks came into existence
in form of a blog post over various technologies including .NET, C#, SQL Server, ASP.NET, ASP.NET MVC, JavaScript,
Angular, Node.js and Visual Studio etc.
The company which is currently registered by a name of Dot Net Tricks Innovation Pvt. Ltd. came into the shape
in 2015. Dot Net Tricks website has an average footfall on the tune of 300k+ per month. The site has become a
cornerstone when it comes to getting skilled-up on .NET technologies and we want to gain the same level of trust
in other technologies. This is what we are striving for.
We have a very large number of trainees who have received training from our platforms and immediately got
placement in some of the reputed firms testifying our claims of providing quality training. The website offers you
a variety of free study material in form of articles.
For a beginner who needs regular guidance, we have a fully packed Master Courses. They are almost equal to
semester courses taught in engineering colleges when it comes to length, breadth of content delivery, the only
difference instead of 5-6 months, they take approx. 16-weekend classes (2 months).
Hands-On Learning courses give you the confidence to code and equally helpful to work in real-life scenarios. This
course is composed of hands-on exercise using IDE or cloud labs so that you can practice each and everything by
yourself. You can learn to code at your own pace, time and place.
The detail about Hands-On Learning courses can be found here: https://www.scholarhat.com
Professionals who don’t have two months’ time and want to get skilled up in least possible time due to some new
project that their company has to take in very near future, we have designed Skill Bootcamps Concept, where you
will get trained on consecutive days in a fast-paced manner, where our full focus is going to be on hands-on
delivery of technological exercises.
Self-paced Courses
Page
Self-paced courses give you the liberty to study at your own pace, time and place. We understand everyone has
their own comfort zone, some of you can afford to dedicate 2 hours a day, some of you not. Keeping this thing in
mind, we created these self-paced courses. While creating these courses we have ensured that quality of courses
doesn’t get compromise at any parameter, and they also will be able to produce the same results as our other
course formats, given the fact you will be able to put your own honest effort.
Dot Net Tricks having a pool of mentors who help the corporate to enhance their employment skills as per
changing technology landscape. Dot Net Tricks offers customized training programs for new hires and experienced
employees through online and classroom mode. As a trusted and resourceful training partner, Dot Net Tricks helps
the corporate to achieve success with its industry-leading instructional design and customer training initiatives.
Learning Platform
We have a very robust technology platform to answer the needs of all our trainees, no matter which program they
enrolled in. We have a very self-intuitive Learning Management System (LMS), which help you in remain focused
and keeping an eye over your progress.
Apart from these, we also provide on-demand Skill bootcamps and personalized project consultation.
3
Page
Dedication
My mother Mrs Vriksha Devi and my wife Reshu Chauhan deserve to have their name on the cover as
much as I do for all their support made this possible. I would like to say thanks to all my family members
Virendra Singh(father), Jaishree and Jyoti(sisters), Saksham and Pranay(sons), friends, to you and to
readers or followers of my blogs at https://www.dotnettricks.com/mentors/shailendra-chauhan to
encourage me to write this book.
-Shailendra Chauhan
4
Page
Introduction
Writing a book has never been an easy task. It takes a great effort, patience and consistency with strong
determination to complete it. Also, one should have a depth knowledge over the subject is going to write.
So, what where my qualification to write this book? My qualification and inspiration come from my enthusiasm
for and the experience with the technology and from my analytic and initiative nature. Being a trainer, analyst,
consultant and blogger, I have thorough knowledge and understandings of .NET technologies. My inspiration and
knowledge have also come from many years of my working experience and research over it.
So, the next question is who this book is for? This book covers useful Interview Questions and Answers on
ASP.NET MVC. This book is appropriate for the novice as well as for senior-level professionals who want to
strengthen their skills before appearing for an interview on ASP.NET MVC. This book is equally helpful to sharpen
their programming skills and understanding ASP.NET MVC in a short time.
This book is not only the ASP.NET MVC interview book but it is more than that. This book helps you to get the
depth knowledge of ASP.NET MVC with a simple and elegant way. This book is updated to the latest version of
ASP.NET MVC5.
I hope you will enjoy this book and find it useful. At the same time, I also encourage you to become a continuing
reader of my blog www.dotnettricks.com and be the part of the discussion. But most importantly practice a lot
and enjoy the technology. That’s what it’s all about.
To get the latest information on ASP.NET MVC, I encourage you to follow the official Microsoft ASP.NET
community website at www.asp.net. I also encourage you to subscribe to my blogs at www.dotnettricks.com that
contains .NET, C#, ASP.NET MVC, EF, jQuery and many more tips, tricks and tutorials.
5
Page
About the Author
Shailendra Chauhan - An Entrepreneur, Author, Architect,
Corporate Trainer, and Microsoft MVP
He is the Founder and CEO of DotNetTricks which is a brand when it comes
to e-Learning. DotNetTricks provides training and consultation over an array
of technologies like Cloud, .NET, Angular, React, Node and Mobile Apps
development. He has been awarded as Microsoft MVP three times in a row
(2016-2018).
He has changed many lives from his writings and unique training programs.
He has a number of most sought-after books to his name which have helped
job aspirants in cracking tough interviews with ease.
Moreover, and to his credit, he has delivered 1000+ training sessions to professionals worldwide in Microsoft
.NET technologies and other technologies including JavaScript, AngularJS, Node.js, React and NoSQL Databases.
In addition, he provides Instructor-led online training, hands-on workshop and corporate training programs.
Shailendra has a strong combination of technical skills and solution development for complex application
architecture with proven leadership and motivational skills have elevated him to a world-renowned status,
placing him at the top of the list of most sought-after trainers.
“I always keep up with new technologies and learning new skills to deliver the best to my students,” says
Shailendra Chauhan, he goes on to acknowledge that the betterment of his followers and enabling his students to
realize their goals are his prime objective and a great source of motivation and satisfaction.
Shailendra Chauhan - “Follow me and you too will have the key that opens the door to success”
6
Page
How to Contact Us
Although the author of this book has tried to make this book as accurate as it possible but if there is something
strikes you as odd, or you find an error in the book please drop a line via e-mail.
• [email protected]
• [email protected]
We always happy to hear from our readers. Please provide your valuable feedback and comments!
You can follow us on YouTube, Facebook, Twitter, LinkedIn and Google Plus or subscribe to RSS feed.
7
Page
Table of Contents
ASP.NET MVC Interview Questions & Answers .............................................................. 1
Release History ...................................................................................................................................................1
About Dot Net Tricks ..........................................................................................................................................2
Dot Net Tricks Training Solutions .......................................................................................................................2
Dedication...........................................................................................................................................................4
Introduction ........................................................................................................................................................5
About the Author................................................................................................................................................6
How to Contact Us ..............................................................................................................................................7
Q6. How to define Attribute Routing for Area in ASP.NET MVC? .................................................................. 28
Q7. What is the difference between Routing and URL Rewriting? ................................................................ 29
Q8. What are Route Constraints in ASP.NET MVC? ....................................................................................... 29
Q9. How route table is created in ASP.NET MVC? ......................................................................................... 30
Q10. What are important namespaces in ASP.NET MVC? ............................................................................... 30
Q11. What is View Engine? .............................................................................................................................. 30
Q12. How does View Engine work? ................................................................................................................. 30
Q13. What is Razor View Engine? .................................................................................................................... 30
Q14. How to make a Custom View Engine? ..................................................................................................... 31
Q15. How to register Custom View Engine in ASP.NET MVC? ......................................................................... 32
Q16. Can you remove default View Engine in ASP.NET MVC? ........................................................................ 32
Q17. What is the difference between Razor and WebForm engine? .............................................................. 32
Q19. What are differences among ViewData, ViewBag, TempData and Session? .......................................... 45
Page
Q20. How to persist data in TempData? .......................................................................................................... 46
Q21. How to control Session behaviour in ASP.NET MVC? ............................................................................. 47
Q22. How TempData is related to Session in ASP.NET MVC? .......................................................................... 48
Q23. What are Action methods in ASP.NET MVC? .......................................................................................... 48
Q24. What is ActionResult and how is it different from others? ..................................................................... 49
Q25. How to make a Non-Action method in ASP.NET MVC?........................................................................... 49
Q26. Can you change the action method name?............................................................................................. 49
Q27. How to restrict an action method to be invoked only by HTTP GET, POST, PUT or DELETE? ................. 50
Q28. How to determine an action method is invoked by HTTP GET or POST? ................................................ 50
Q29. How to determine an AJAX request? ...................................................................................................... 51
References ..................................................................................................................... 83
11
Page
1
ASP.NET MVC Introduction
Q1. What is MVC?
Ans. MVC stands for Model-View-Controller. It is a software design pattern which was introduced in the 1970s.
Also, MVC pattern forces a separation of concerns, it means domain model and controller logic are decoupled
from the user interface (view). As a result, maintenance and testing of the application become simpler and easier.
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 processes 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.
12
Page
Today, this pattern is used by many popular frameworks like as Ruby on Rails, Spring Framework, Apple iOS
Development and ASP.NET MVC.
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 persisted. So, it can be SQL server, Oracle, XML, text file or anything else. The repository is not a Data
Access Layer but it refers to a location for storage, often for safety or preservation.
Model - The Model represents a set of classes that describe 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 others by an interface.
Also, the presenter does not manage the incoming request traffic as a controller.
13
Page
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.
Model - The Model represents a set of classes that describe 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 help 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.
14
Page
This pattern is commonly used by the WPF, Silverlight, Caliburn, nRoute etc.
The Model in ASP.NET MVC can be broken down into several different layers as given below:
1. Objects or ViewModel or Presentation Layer - This layer contains simple objects or complex objects which
are used to specify a strongly-typed view. These objects are used to pass data from controller to strongly-
typed view and vice versa. The classes for these objects can have specific validation rules which are
defined by using data annotations. Typically, these classes have those properties which you want to
display on corresponding view/page.
2. Business Layer - This layer helps you to implement your business logic and validations for your application.
15
This layer makes use of Data Access Layer for persisting data into the database. Also, this layer is directly
invoked by the Controller to do processing on input data and sent back to view.
Page
3. Data Access Layer - This layer provides objects to access and manipulate the database of your application.
Typically, this layer is made by using ORM tools like Entity Framework or NHibernate etc.
By default, models are stored in the Models folder of an ASP.NET MVC application.
The view 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, 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 processes the user's data with the
help of Model and passing the results back to the View.
By default, controllers have stored in the Controllers folder an ASP.NET MVC application.
Q8. How Model, View and Controller communicate with each other in ASP.NET MVC?
Ans. There are following rules for communication among Model, View and Controller:
• Separation of concern - MVC design pattern divides the ASP.NET MVC application into three main aspects
Model, View and Controller which make it easier to manage the application complexity.
• TDD - The MVC framework brings better support to test-driven development.
• Extensible and pluggable - MVC framework components were designed to be pluggable and extensible
and therefore can be replaced or customized easier than 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 behaviours 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 provider's 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 the application to
be more addressable from the eyes of search engines and clients and can help in search engine
optimization.
ASP.NET MVC1
ASP.NET MVC2
• Support for DataAnnotations Attributes to apply model validation on both client and server sides
• Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE
• Areas for partitioning a large application into modules
• Asynchronous controllers
ASP.NET MVC3
ASP.NET MVC4
ASP.NET MVC5
• One ASP.NET
• ASP.NET Identity
Page
• ASP.NET Scaffolding
• Authentication filters - run prior to authorization filters in the ASP.NET MVC pipeline
• Bootstrap in the MVC template
• ASP.NET WEB API2
Q11. What is the difference between 3-layer architecture and MVC architecture?
Ans. 3-layer architecture separates the application into 3 components which consist of Presentation Layer
Business Layer and Data Access Layer. In 3-layer architecture, the user interacts with the Presentation layer. 3-
layer is a linear architecture.
MVC architecture separates the application into three components which consist of Model, View and Controller.
In MVC architecture, the user interacts with the controller with the help of view. MVC is a triangle architecture.
MVC does not replace 3-layer architecture. Typically, 3-layer and MVC are used together and MVC acts as the
Presentation layer.
Q12. What is the difference between ASP.NET WebForm and ASP.NET MVC?
Ans. The main differences between ASP.NET Web Form and ASP.NET MVC are given below:
ASP.NET Web Form has server controls. ASP.NET MVC has HTML helpers.
ASP.NET Web Form has state management (like as ASP.NET MVC has no automatic state management
Page
• ViewModel contain fields that are represented in the view (for LabelFor, EditorFor, DisplayFor helpers)
• ViewModel can have specific validation rules using data annotations.
• ViewModel can have multiple entities or objects from different data models or data source.
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.
20
Page
Page
21
2. Controller Initialization - The MvcHandler initiates the real processing inside ASP.NET MVC pipeline by using
the ProcessRequest method. This method uses the IControllerFactory instance (default is
System.Web.Mvc.DefaultControllerFactory) to create corresponding controller.
into ViewResult category and another result type which returns only data either in text format, binary
Page
23
Page
2
Routing and View Engines
Q1. What is Routing in ASP.NET MVC?
Ans. Routing is a pattern matching system that monitors the incoming request and figure out what to do with
that request. At runtime, the Routing engine uses 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.
24
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
Page
Always remember route name should be unique across the entire application. Route name can’t be duplicate.
In the 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 mean if you will not provide the values for controller
or action or id defined in the pattern then these values will be served by the routing system.
Suppose your web application is running on www.example.com then the URL pattern for your 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 the 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 the more specific route on the top order while defining the routes, since routing system checks
the incoming URL pattern form the top and as it gets the matched route it will consider that. It will not be checked
25
1. Controller level routing – You can define routes at controller level which apply to all actions within the
controller unless a specific route is added to an action.
[RoutePrefix("MyHome")]
[Route("{action=index}")] //default action
public class HomeController: Controller
{
//new route: /MyHome/Index
public ActionResult Index()
{
return View();
}
2. Action level routing – You can define routes at action level which apply to a specific action within the
controller.
{
ViewBag.Message = "Your application description page.";
return View();
}
//route: /Home/Contact
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
Note:
For example, resources often contain child resources like Clients have ordered, movies have actors, books have
authors and so on. It’s natural to create URIs that reflects these relations like as /clients/1/orders
This type of URI is difficult to create using convention-based routing. Although it can be done, the results don’t
scale well if you have many controllers or resource types.
With attribute routing, it’s pretty much easy to define a route for this URI. You simply add an attribute to the
controller action as:
[Route("clients/{clientId}/orders")]
public IEnumerable<Order> GetOrdersByClient(int clientId)
{
//TO DO
}
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
Page
//enabling attribute routing
routes.MapMvcAttributeRoutes();
}
}
//convention-based routing
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional });
}
}
[RouteArea("Admin")]
[RoutePrefix("menu")]
[Route("{action}")]
public class MenuController: Controller
{
// route: /admin/menu/login
public ActionResult Login()
{
return View();
}
// route: /admin/menu/products
[Route("products")]
public ActionResult GetProducts()
{
return View();
}
28
Page
// route: /categories
[Route("~/categories")]
public ActionResult Categories()
{
return View();
}
}
• 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 a new one while routing never rewrite your old URL to the new
one but it maps 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.
new
{
Page
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}, // Default values for parameters
new { id = @"\d+" } //Restriction for id
);
}
Now for this route, routing engine will consider only those URLs which have only numeric id like as
http://example.com/Admin/Product/1 else it will consider that URL is not matched with this route.
• System.Web.MVC - This namespace contains classes and interfaces that support the MVC pattern for
ASP.NET Web applications. This namespace includes classes that represent controllers, controller
factories, action results, views, partial views, and model binders.
• System.Web.Mvc.Ajax - This namespace contains classes that support Ajax scripting in an ASP.NET MVC
application. The namespace includes support for Ajax scripts and Ajax option settings as well.
• System.Web.Mvc.Html – This namespace contains classes that help render HTML controls in an MVC
application. This namespace includes classes that support forms, input controls, links, partial views, and
validation.
1. ViewEngine class - This class implements the IViewEngine interface and responsible for locating view
templates.
2. View class - This class implements the IView interface and responsible for combining the template with
data from the current context and convert it to output HTML markup.
3. Template parsing engine - This parses the template and compiles the view into executable code.
Ans. 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 advances syntax that is compact, expressive and reduces typing.
Page
Razor syntax is easy to learn and much cleaner than Web Form syntax. Razor uses @ symbol to write markup as:
@Html.ActionLink("SignUp", "SignUp")
//Perform Replacements
string parsedcontents = Parse(rawcontents, viewContext.ViewData);
writer.Write(parsedcontents);
}
Ans. The main differences between ASP.NET Web Form and ASP.NET MVC are given below:
Page
Razor View Engine WebForm View Engine
Razor Engine is an advanced view engine that was WebForm Engine is the default view engine for the
introduced with MVC3. This is not a new language Asp.net MVC that is included with Asp.net MVC from the
but it is a new markup syntax. beginning.
The namespace for Razor Engine is The namespace for WebForm Engine is
System.Web.Razor. System.Web.Mvc.WebFormViewEngine.
The file extensions used with Razor Engine are The file extensions used with Web Form Engine are also
different from Web Form Engine. It has .cshtml like Asp.net Web Forms. It has .aspx extension for views,
(Razor with C#) or .vbhtml (Razor with VB) .ascx extension for partial views & editor templates and
extension for views, partial views, editor templates .master extension for layout/master pages.
and for layout pages.
Razor has new and advances syntax that is compact, WebForm Engine has the same syntax as Asp.net Web
expressive and reduces typing. Forms uses for .aspx pages.
Razor syntax is easy to learn and much cleaner than WebForm syntax is borrowed from Asp.net Web Forms
Web Form syntax. Razor uses @ symbol to make syntax that is mixed with HTML and sometimes makes a
the code like as: view messy. Webform uses <% and %> delimiters to make
@Html.ActionLink("SignUp", "SignUp") the code like as:
<%: Html.ActionLink("SignUp", "SignUp") %>
By default, Razor Engine prevents XSS attacks WebForm Engine does not prevent XSS attacks means any
(Cross-Site Scripting Attacks) means it encodes the script saved in the database will be fired while rendering
script or HTML tags like <, > before rendering to the page
view.
Razor Engine is a little bit slow as compared to WebForm Engine is faster than Razor Engine.
WebForm Engine.
Razor Engine doesn't support design mode in the WebForm engine support design mode in the visual studio
visual studio means you cannot see your page look means you can see your page look and feel without
and feel. running the application.
Razor Engine support TDD (Test Driven Web Form Engine doesn't support TDD (Test Driven
Development) since it does not depend on Development) since it depends on System.Web.UI.Page
System.Web.UI.Page class. class which makes the testing complex.
33
Page
3
Helpers and Views
Q1. What are HTML Helpers in ASP.NET MVC?
Ans. An HTML Helper is just a method that returns an 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 created in the same view by using the Razor @helper tag. These helpers
can be reused only on the same view.
<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-
34
• Standard Html Helpers - These helpers are used to render the most common types of HTML elements like
Page
as HTML text boxes, checkboxes etc. A list of most common standard HTML helpers is given below:
HTML Element Example
TextBox @Html.TextBox("Textbox1", "val")
Output:
<input id="Textbox1" name="Textbox1" type="text" value="val" />
TextArea @Html.TextArea("Textarea1", "val", 5, 15, null)
Output:
<textarea cols="15" id="Textarea1" name="Textarea1"
rows="5">val</textarea>
Password @Html.Password("Password1", "val")
Output:
<input id="Password1" name="Password1" type="password" value="val" />
Hidden Field @Html.Hidden("Hidden1", "val")
Output:
<input id="Hidden1" name="Hidden1" type="hidden" value="val" />
CheckBox @Html.CheckBox("Checkbox1", false)
Output:
<input id="Checkbox1" name="Checkbox1" type="checkbox" value="true" />
<input name="myCheckbox" type="hidden" value="false" />
RadioButton @Html.RadioButton("Radiobutton1", "val", true)
Output:
<input checked="checked" id="Radiobutton1" name="Radiobutton1"
type="radio" value="val" />
Drop-down list @Html.DropDownList (“DropDownList1”, new SelectList(new [] {"Male",
"Female"}))
Output:
<select id="DropDownList1" name="DropDownList1">
<option>M</option>
<option>F</option>
</select>
Multiple-select Html.ListBox(“ListBox1”, new MultiSelectList(new [] {"Cricket", "Chess"}))
Output:
<select id="ListBox1" multiple="multiple" name="ListBox1">
<option>Cricket</option>
<option>Chess</option>
</select>
• Strongly Typed HTML Helpers - These helpers are used to render the most common types of HTML
elements in strongly typed view like as HTML text boxes, checkboxes etc. The HTML elements are created
based on model properties.
The strongly typed HTML helpers work on lambda expression. The model object is passed as a value to a
lambda expression, and you can select the field or property from model object to be used to set the id,
35
name and value attributes of the HTML helper. A list of most common strongly-typed HTML helpers is
given below:
Page
HTML Element Example
TextBox @Html.TextBoxFor(m=>m.Name)
Output:
<input id="Name" name="Name" type="text" value="Name-val" />
TextArea @Html.TextArea(m=>m.Address , 5, 15, new{}))
Output:
<textarea cols="15" id="Address" name=" Address "
rows="5">Addressvalue</textarea>
Password @Html.PasswordFor(m=>m.Password)
Output:
<input id="Password" name="Password" type="password"/>
Hidden Field @Html.HiddenFor(m=>m.UserId)
Output:
<input id=" UserId" name=" UserId" type="hidden" value="UserId-val" />
CheckBox @Html.CheckBoxFor(m=>m.IsApproved)
Output:
<input id="Checkbox1" name="Checkbox1" type="checkbox" value="true" />
<input name="myCheckbox" type="hidden" value="false" />
RadioButton @Html.RadioButtonFor(m=>m.IsApproved, "val")
Output:
<input checked="checked" id="Radiobutton1" name="Radiobutton1"
type="radio" value="val" />
Drop-down list @Html.DropDownListFor(m => m.Gender, new SelectList(new [] {"Male",
"Female"}))
Output:
<select id="Gender" name="Gender">
<option>Male</option>
<option>Female</option>
</select>
Multiple-select Html.ListBoxFor(m => m.Hobbies, new MultiSelectList(new [] {"Cricket",
"Chess"}))
Output:
<select id="Hobbies" multiple="multiple" name="Hobbies">
<option>Cricket</option>
<option>Chess</option>
</select>
• Templated HTML Helpers - These helpers figure out what HTML elements are required to render based
on the properties of your model class. This is a very flexible approach for displaying data to the user,
although it requires some initial care and attention to set up. To set up proper HTML element with
Templated HTML Helper, make use of DataType attribute of DataAnnotation class.
36
For example, when you use DataType as Password, A templated helper automatically render a Password
type HTML input element.
Page
Templated Helper Example
Display Renders a read-only view of the specified model property and selects an
appropriate HTML element based on property’s data type and metadata.
Html.Display("Name")
DisplayFor Strongly typed version of the previous helper
Html.DisplayFor(m => m. Name)
Editor Renders an editor for the specified model property and selects an
appropriate HTML element based on property’s data type and metadata.
Html.Editor("Name")
EditorFor Strongly typed version of the previous helper
Html.EditorFor(m => m. Name)
3. Custom Html Helpers - You can also create your own custom helper methods by creating an extension
method on the HtmlHelper class or by creating static methods within a utility class.
buttonText)
{
string str = "<input type=\"submit\" value=\"" + buttonText + "\"
/>";
return new MvcHtmlString(str);
}
//Readonly Strongly-Typed TextBox Helper
public static MvcHtmlString TextBoxFor<TModel, TValue>(this
HtmlHelper<TModel> htmlHelper, Expression<Func<TModel,
TValue>>expression, bool isReadonly)
{
MvcHtmlString html = default(MvcHtmlString);
if (isReadonly)
{
html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
expression, new { @class = "readOnly",
@readonly = "read-only" });
}
else
{
html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
expression);
}
return html;
37
}
}
Page
Q3. What are Url Helpers?
Ans. Url helpers allow you to render HTML links and raw URLs. The output of these helpers is dependent on
the routing configuration of your ASP.NET MVC application.
Suppose, you have the following lines of code somewhere in the controller action rendering a view:
In the first error, there is no key to associate this error with a specific property. In the second error, there is a
key named as “Title” to associate this error for model property Title.
Hence, when the boolean type parameter value is true then ValidationSummary will display only model-level
errors and exclude property-level errors. It will display Model-level and property-level errors when the boolean
type parameter value is false.
Property Description
Url Specify the URL that will be requested from the server.
Specify a message that will be displayed in a confirm dialog to the end user. When
Confirm the user clicks on the OK button in the confirmation dialog, the Ajax call performs.
Specify a JavaScript function name which is called at the beginning of the Ajax
OnBegin request.
OnComplete Specify a JavaScript function name which is called at the end of the Ajax request.
Specify a JavaScript function name which is called when the Ajax request is
OnSuccess successful.
OnFailure Specify a JavaScript function name which is called if the Ajax request fails.
Specify progress message container’s Id to display a progress message or
LoadingElementId animation to the end user while an Ajax request is being made.
Specify a time duration in milliseconds that controls the duration of the progress
LoadingElementDuration message or animation.
Specify the target container’s Id that will be populated with the HTML returned by
UpdateTargetId the action method.
Specify the way of populating the target container. The possible values are
InsertionMode InsertAfter, InsertBefore and Replace (which is the default).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
You can use a layout to define a common template for your site. A layout can be declared at the top of view as:
@{
Layout = "~/Views/Shared/SiteLayout.cshtml";
}
@section header{
<h1>Header Content</h1>
}
You can render above defined section header on the content page as given below:
@RenderSection("header")
By default, sections are mandatory. To make sections optional just provides the second parameter value as false,
which is a Boolean value.
@RenderSection("header",false)
Note: A view can define only those sections that are referred to in the layout page otherwise an exception will be
40
thrown.
Page
Q11. What are RenderBody and RenderPage in ASP.NET MVC?
Ans. RenderBody method exists in the Layout page to render child page/view. It is just like the
ContentPlaceHolder on master page. A layout page can have only one RenderBody method.
<body>
@RenderBody()
@RenderPage("~/Views/Shared/_Header.cshtml")
@RenderPage("~/Views/Shared/_Footer.cshtml")
@RenderSection("scripts",false)
@section scripts{
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
}
</body>
The renderpage method also exists in the Layout page to render another page exists in your application. A layout
page can have multiple RenderPage methods.
@RenderPage("~/Views/Shared/_Header.cshtml")
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
Styles.Render and Scripts.Render generate multiple style and script tags for each item in the CSS bundle and
Script bundle when optimizations are disabled. When optimizations are enabled, Styles.Render and
Scripts.Render generate a single style and script tag to a version-stamped URL which represents the entire
bundle for CSS and Scripts.
41
Page
Q13. How to enable and disable optimizations in ASP.NET MVC?
Ans. You can enable and disable optimizations by setting EnableOptimizations property of BundleTable class
to true or false within Global.asax.cs file as shown below.
By default, ASP.NET MVC project has a _ViewStart.cshtml file in the Views directory and it specifies a default
layout for your ASP.NET MVC application as shown below:
@{
Layout = "~/Views/Shared/Layout.cshtml";
}
Since this code runs before any view, hence a view can override the Layout property and choose a different layout.
1. Using _ViewStart file in the root directory of the Views folder: The _ViewStart file within Views folder is
used to server the default Layout page for your ASP.NET MVC application. You can also change the default
rendering of layouts within _ViewStart file based on the controller as shown below:
@{
var controller =
HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToSt
ring();
layout = "~/Views/Shared/_AdminLayout.cshtml";
}
Page
else
{
layout = "~/Views/Shared/_Layout.cshtml";
}
Layout = layout;
}
@{
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
• BundleConfig.cs - This is used to create and register bundles for CSS and JS files. By default, various
bundles are added in these files including jQuery, jQueryUI, jQuery Validation, Modernizr, and Site CSS.
• FIlterConfig.cs - This is used to register global MVC filters like error filters, actions filters etc. By default, it
contains a HandleErrorAttribute filter.
• RouteConfig.cs - This is used to register various route patterns for your ASP.NET MVC application. By
default, one route is registered here named as Default Route.
• WebApiConfig.cs - This is used to register various WEB API routes like as ASP.NET MVC, as well as set any
additional WEB API configuration settings.
1. Return View() - This tells MVC to generate HTML to be displayed for the specified view and sends it to the
browser. This acts like as Server.Transfer() in ASP.NET WebForm.
2. Return RedirectToAction() - This tells MVC to redirect to specified action instead of rendering HTML. In this
case, the browser receives the redirect notification and make a new request for the specified action. This acts
like as Response.Redirect() in ASP.NET WebForm.
Moreover, RedirectToAction constructs a redirect URL to a specific action/controller in your application and
use the route table to generate the correct URL. RedirectToAction causes the browser to receive a 302
redirect within your application and gives you an easier way to work with your route table.
3. Return Redirect() - This tells MVC to redirect to specified URL instead of rendering HTML. In this case, the
browser receives the redirect notification and make a new request for the specified URL. This also acts like as
Response.Redirect() in ASP.NET WebForm. In this case, you have to specify the full URL to redirect.
Moreover, redirect also cause the browser to receive a 302 redirect within your application, but you have to
construct the URLs yourself.
4. Return RedirectToRoute() - This tells MVC to look up the specifies route into the Route table that is defined
in global.asax and then redirect to that controller/action defined in that route. This also make a new request
like RedirectToAction().
Note:
1. Return View doesn't make a new request, it just renders the view without changing URLs in the browser's
address bar.
44
2. Return RedirectToAction makes a new request and URL in the browser's address bar is updated with the
Page
Q19. What are differences among ViewData, ViewBag, TempData and Session?
Ans. In ASP.NET MVC there are three ways - ViewData, ViewBag and TempData to pass data from the controller
to view and in next request. Like WebForm, you can also use Session to persist data during a user session.
ViewData
ViewBag
• ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
• Basically, it is a wrapper around the ViewData and also used to pass data from controller to the corresponding
view.
• Its life also lies only during the current request.
• If redirection occurs then its value becomes null.
• It doesn’t require typecasting for getting data.
45
Page
TempData
• TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives
session.
• TempData is used to pass data from current request to subsequent request (means redirecting from one
page to another).
• Its life is very short and lies only till the target view is fully loaded.
• It’s required typecasting for getting data and check for null values to avoid error.
• It’s used to store only one-time messages like error messages, validation messages.
Session
• The session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it persists
data for a user session until it is timeout (by default session timeout is 20 minutes).
• The session is valid for all requests, not for a single redirect.
• It’s also required typecasting for getting data and check for null values to avoid error.
• void Keep() - Calling this method within the current action ensures that all the items in TempData are not
Page
• void Keep(string key) - Calling this method within the current action ensures that specific item in
TempData is not removed at the end of the current request.
If some of the controllers of your ASP.NET MVC application are not using session state features, you can disable
session for that controller and can gain slight performance improvement of your application. You can simplify
session state for your application by using available options for session state.
In ASP.NET MVC4, SessionState attribute provides you more control over the behaviour of session-state by
specifying the value of SessionStateBehavior enumeration as shown below:
Value Description
Default The default ASP.NET behaviour is used to determine the session state behaviour.
Disabled Session state is disabled entirely.
ReadOnly Read-only session state behaviour is enabled.
Required Full read-write session state behaviour is enabled.
47
Page
Q22. How TempData is related to Session in ASP.NET MVC?
Ans. In ASP.NET MVC, TempData uses session state for storing the data values across requests. Hence, when
you will be disabled the session state for the controller, it will throw the exception as shown below:
1. ViewResult - Returns a ViewResult which renders the specified or default view by using controller View()
helper method.
2. PartialViewResult - Returns a PartialViewResult which renders the specified or default partial view (means
a view without its layout) by using controller PartialView() helper method.
3. RedirectResult - Returns a RedirectResult which Issues an HTTP 301 or 302 redirection to a specific URL
by using controller Redirect() helper method.
4. RedirectToRouteResult - Returns a RedirectToRouteResult which Issues an HTTP 301 or 302 redirection
to an action method or specific route entry by using controller RedirectToAction(),
RedirectToActionPermanent(), RedirectToRoute(), RedirectToRoutePermanent() helper methods.
48
5. ContentResult - Returns a ContentResult which renders raw text like as "Hello, DotNet Tricks!" by using
controller Content() helper method.
Page
6. JsonResult - Returns a JsonResult which serializes an object in JSON format (like as "{ "Message": Hello,
World! }") and renders it by using controller Json() helper method.
7. JavaScriptResult - Returns a JavaScriptResult which renders a snippet of JavaScript code like as "function
hello() { alert(Hello, World!); }" by using controller JavaScript() helper method. This is used only in AJAX
scenarios.
8. FileResult - Returns a FileResult which renders the contents of a file like as PDF, DOC, Excel etc. by using
controller File() helper method.
9. EmptyResult - Returns no result returned by an action. This has no controller helper method.
10. HttpNotFoundResult - Returns an HttpNotFoundResult which renders a 404 HTTP Status Code response
by using controller HttpNotFound() helper method.
11. HttpUnauthorizedResult - Returns an HttpUnauthorizedResult which renders a 401 HTTP Status Code
(means "not authorized") response. This has no controller helper method. This is used for authentication
(forms authentication or Windows authentication) to ask the user to log in.
12. HttpStatusCodeResult - Returns an HttpStatusCodeResult which renders a specified HTTP code response.
This has no controller helper method.
[NonAction]
public void DoSomething()
{
// Method logic
}
49
Now, DoSomething action will be identified and called by the name DoAction.
Q27. How to restrict an action method to be invoked only by HTTP GET, POST, PUT or
DELETE?
Ans. By default, each and every action method can be invoked by an HTTP request (i.e. GET, PUT, POST, and
DELETE). But you can restrict an action to be invoked only by a specific HTTP request by applying HttpGet or
HttpPost or HttpPut or HttpDelete attribute.
If you want to restrict an action method for HTTP Get request only then decorate it with HttpGet action method
selector attribute as given below:
[HttpGet]
public ActionResult Index()
{
//TODO:
return View();
}
51
Page
4
Forms and Validations
Q1. What are Data Annotations in ASP.NET MVC?
Ans. Data validation is a key aspect for developing a web application. In Asp.net MVC, we can easily apply
validation to the web application by using Data Annotation attribute classes to the model class. Data Annotation
attribute classes are present in System.ComponentModel.DataAnnotations namespace and are available to
Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms and also to Entity framework
ORM models.
Data Annotations help us to define the rules to the model classes or properties for data validation and displaying
suitable messages to end users.
In ASP.NET MVC, there are two ways to validate a model on the server side:
1. Explicit Model Validation – This is the traditional way to validate the model data by using If...else...If
52
statement. In this way, you need to check your model property values one by one for your desired result.
Page
If model property values are unexpected, inject error messages within ModelState.
class HomeController : Controller
{
[HttpPost]
public ActionResult ExplicitServer(UserViewModel model)
{
//Write custom logic to validate UserViewModel
if (string.IsNullOrEmpty(model.UserName))
{
ModelState.AddModelError("UserName", "Please enter your
name");
}
if (!string.IsNullOrEmpty(model.UserName))
{
Regex emailRegex = new Regex(".+@.+\\..+");
if (!emailRegex.IsMatch(model.UserName))
ModelState.AddModelError("UserName", "Please enter correct
email address");
}
2. Model Validation with Data Annotations - Data Annotations was introduced with .NET 3.5 SP1. It has a
set of attributes and classes defined in the System.ComponentModel.DataAnnotations assembly. Data
Annotations allow us to decorate model classes with metadata. This metadata describes a set of rules that
are used to validate a property.
ModelState.IsValid property you can verify model state. It returns true if there is no error in ModelState else
Page
returns false.
[HttpPost]
public ActionResult DoSomething(UserViewModel model)
{
if (ModelState.IsValid)
{
//TODO:
}
return View();
}
For client-side validation, the values of above both the keys must be true. When we create a new project using
Visual Studio in MVC3 or MVC4, by default the values of both the keys are set to true.
We can also enable the client-side validation programmatically. For this we need to do code within the
Application_Start() event of the Global.asax, as shown below.
We can also enable or disable client-side validation for a specific view. For this, we required to enable or disable
client-side validation inside a Razor code block as shown below. This option will override the application level
settings for that specific view.
@using MvcApp.Models
@{
ViewBag.Title = "About";
HtmlHelper.ClientValidationEnabled = false;
}
// Microsoft CDN
<scripttype="text/javascript"src="http://ajax.microsoft.com/ajax/jquery/jquery-
1.9.1.min.js"></script>
// JQuery CDN
<scripttype="text/javascript"src="http://code.jquery.com/jquery-
1.9.1.min.js"></script>
Advantages
A bundle is a logical group of files that are loaded with a single HTTP request. You can create style and script
bundle for CSS and Java Scripts respectively by calling BundleCollection class Add() method. All bundles are created
within BundleConfig.cs file.
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery-1.7.1.min.js",
"~/Scripts/jquery.validate.min.js",
55
"~/Scripts/jquery.validate.unobtrusive.min.js"));
Page
}
}
Minification is a technique for removing unnecessary characters (like white space, newline, tab) and comments
from the JavaScript and CSS files to reduce the size which cause improved load times of a webpage. There are so
many tools for minifying the js and CSS files. JSMin and YUI Compressor are the two most popular tools for
minifying js and CSS files.
Suppose you have below CSS and JS files on the layout page and run the application in chrome browser and test
no of request and loading time using chrome developer tools as shown below.
In this test, there are 7 requests, total data size is 3.96KB and loading time is approximate 296ms.
When you will run the above application with Bundling and Minification of CSS and js files and test no of request
and loading time using chrome developer tools as shown below.
@Styles.Render("~/Content/CSS")
56
@Scripts.Render("~/bundles/jquery")
Page
In this test, there are only 3 requests, total data size is 2.67KB and loading time is approximate 80ms. In this way,
by using bundling and minification you have reduced the total no of the request, size and loading time.
But bundles automatically takes care of this problem by adding a hash code to each bundle as a query parameter
to the URL as shown below. Whenever you change the content of CSS and JS files then a new hash code will be
generated and rendered to the page automatically. In this way, the browser will see a different Url and will fetch
the new copy of CSS and JS.
We can use a partial view to display blog comments, product category, social bookmarks buttons, a dynamic ticker,
calendar etc.
It is best practice to create a partial view in the shared folder and partial view name is preceded by "_", but it is
not mandatory. The "_" before view name specify that it is a reusable component i.e. partial view.
57
Page
Q11. How do you return a partial view from the controller?
Ans. return PartialView(options); where options could be a Model or a View name
Q12. What are different ways of rendering a Partial View in ASP.NET MVC?
Ans. There are four methods for rendering a partial view in ASP.NET MVC These are RenderPartial,
RenderAction, Partial and Action helper methods.
Html.RenderPartial
• This method result will be directly written to the HTTP response stream means it used the same TextWriter
object as used in the current webpage/template.
• This method returns void.
• Simple to use and no need to create any action.
• RenderPartial method is useful when the displaying data in the partial view is already in the corresponding
view model. For example: In a blog to show comments of an article, you can use RenderPartial method
since an article information with comments is already populated in the view model.
@{Html.RenderPartial("_Comments");}
• This method is faster than Partial method since its result is directly written to the response stream which
makes it fast.
Html.RenderAction
• This method result will be directly written to the HTTP response stream means it used the same TextWriter
object as used in the current webpage/template.
• For this method, we need to create a child action for the rendering the partial view.
• RenderAction method is useful when the displaying data in the partial view is independent of the
corresponding view model. For example: In a blog to show category list on each and every page, we would
like to use RenderAction method since the list of the category is populated by the different model.
@{Html.RenderAction("Category","Home");}
• This method is the best choice when you want to cache a partial view.
• This method is faster than Action method since its result is directly written to the HTTP response stream
which makes it fast.
Html.Partial
is already in the corresponding view model. For example: In a blog to show comments of an article, you
Page
can use Partial method since an article information with comments is already populated in the view
model.
@Html.Partial("_Comments")
Html.Action
@{Html.Action("Category","Home");}
• This method is also the best choice when you want to cache a partial view.
59
Page
Each MVC area has its own folder structure which allows us to keep separate controllers, views, and models. This
also helps the multiple developers to work on the same web application without interfere with one another.
Always remember the order of registering the Areas must be on top so that all of the settings, filters and routes
registered for the applications will also apply on the Areas.
[ChildActionOnly]
public ActionResult MenuBar()
{
//TODO:
return PartialView();
}
A child action is invoked by using @Html.RenderAction or @Html.Action helper methods from inside of a view.
Scaffolding consists of page templates, entity page templates, field page templates, and filter templates. These
templates are called Scaffold templates and allow you to quickly build a functional data-driven Web site.
Steps to create ASP.NET MVC CRUD operations using scaffolding in ASP.NET MVC:
Page
62
Page
5
Security and Filters
Q1. What are ASP.NET MVC Filters and Attributes?
Ans. ASP.NET MVC provides a simple way to inject your piece of code or logic either before or after an action
is executed. This is achieved by decorating the controllers or actions with ASP.NET MVC attributes or custom
attributes. An attribute or custom attribute implements the ASP.NET MVC filters (filter interface) and can contain
your piece of code or logic. You can make your own custom filters or attributes either by implementing ASP.NET
MVC filter interface or by inheriting and overriding methods of ASP.NET MVC filter attribute class if available.
Typically, Filters are used to perform the following common functionalities in your ASP.NET MVC application.
1. Custom Authentication
2. Custom Authorization (User-based or Role-based)
3. Error handling or logging
4. User Activity Logging
5. Data Caching
6. Data Compression
1. Authentication Filters - This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is
used to create CustomAuthentication filter. The definition of this interface is given below-
void OnAuthenticationChallenge(AuthenticationChallengeContext
filterContext);
}
You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as shown
below-
63
{
public void OnAuthentication(AuthenticationContext filterContext)
{
filterContext.HttpContext.Response.Write("Authentication
Filter<br/>");
}
//Runs after the OnAuthentication method
public void OnAuthenticationChallenge(AuthenticationChallengeContext
filterContext)
{
//TODO: Additional tasks on the request
}
}
2. Authorization Filters - The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter
interface. The definition of this interface is given below-
The AuthorizeAttribute class provides the following methods to override in the CustomAuthorize attribute
class.
In this way, you can make your CustomAuthorize filter attribute either by implementing an IAuthorizationFilter
interface or by inheriting and overriding above methods of AuthorizeAttribute class.
3. Action Filters - Action filters are executed before or after an action is executed. The IActionFilter interface is
used to create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted which
will be executed before or after an action is executed respectively.
4. Result Filters - Result filters are executed before or after generating the result for an action. The Action Result
Page
5. Exception Filters - Exception filters are executed when an exception occurs during the actions execution or
filters execution. The IExceptionFilter interface is used to create an Exception Filter which provides
OnException method which will be executed when an exception occurs during the actions execution or filters
execution.
The HandleErrorAttribute class is one example of an exception filter which implements IExceptionFilter.
When HandleError filter receives the exception it returns an Error view located in the Views/Shared folder
of your ASP.NET MVC application.
• Authentication filters
• Authorization filters
• Action filters
• Result filters
1. Global level - By registering your filter into Application_Start event of Global.asax.cs file with the help of
FilterConfig class.
65
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
2. Controller level - By putting your filter on the top of the controller name as shown below-
[Authorize(Roles = "Admin")]
public class AdminController: Controller
{
//TODO:
}
3. Action level - By putting your filter on the top of the action name as shown below-
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
protection="All"
timeout="30"
name=".ASPXAUTH"
path="/"
requireSSL="false"
slidingExpiration="true"
defaultUrl="default.aspx"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" />
</authentication>
</system.web>
66
Page
The FormsAuthentication class creates the authentication cookie automatically when SetAuthCookie() or
RedirectFromLoginPage() methods are called. The value of authentication cookie contains a string representation
of the encrypted and signed FormsAuthenticationTicket object.
You can create the FormsAuthenticationTicket object by specifying the cookie name, version of the cookie,
directory path, issue date of the cookie, expiration date of the cookie, whether the cookie should be persisted,
and optionally user-defined data as shown below:
Now, you can encrypt this ticket by using the Encrypt method FormsAuthentication class as given below:
Ans. When standard types of authentication do not meet your requirements, you need to modify an
Page
authentication mechanism to create a custom solution. A user context has principal which represents the identity
and roles for that user. A user is authenticated by its identity and assigned roles to a user determine about
authorization or permission to access resources.
ASP.NET provides IPrincipal and IIdentity interfaces to represents the identity and role for a user. You can create
a custom solution by evaluating the IPrincipal and IIdentity interfaces which are bound to the HttpContext as well
as the current thread.
A user will be authenticated if IsAuthenticated property returns true. For authenticating a user you can use one
of the following two ways:
1. Thread.CurrentPrincipal.Identity.IsAuthenticated
2. HttpContext.Current.User.Identity.IsAuthenticated
ASP.NET MVC provides Authorization filter to authorize a user. This filter can be applied to an action, a controller,
or even globally. This filter is based on AuthorizeAttribute class. You can customize this filter by overriding
OnAuthorization() method as shown below:
if (!String.IsNullOrEmpty(Roles))
{
if (!CurrentUser.IsInRole(Roles))
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Error", action =
"AccessDenied" }));
if (!String.IsNullOrEmpty(Users))
{
if (!Users.Contains(CurrentUser.UserId.ToString()))
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Error", action =
"AccessDenied" }));
}
}
Page
}
}
}
Now you can apply this custom authorization filter at controller or action level for authorization as shown below:
[CustomAuthorize(Roles= "Admin")]
public class AdminController : BaseController
{
public ActionResult Index()
{
return View();
}
}
ValidateInput attribute can enable or disable input validation at the controller level or at any action method.
[ValidateInput(false)]
public class HomeController: Controller
{
public ActionResult AddArticle()
{
return View();
}
}
ValidateInput attribute allows the Html input for all the properties and that is unsafe. Since you have enabled
Html input for only one-two properties then how to do this. To allow Html input for a single property, you should
use AllowHtml attribute.
[AllowHtml]
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
}
70
Page
Q10. What is caching and when to use it?
Ans. Caching is a most important aspect of the high-performance web application. Caching provides a way of
storing frequently accessed data and reusing that data. Practically, this is an effective way for improving web
application’s performance.
ViewBag.Message = DateTime.Now.ToString();
return View();
}
}
The output of the Index() action method will be cached for 20 seconds. If you will not define the duration, it will
cache it for by default cache duration 60 sec.
By default, content is cached in three locations: the web server, any proxy servers, and the user's browser. You
can control the content's cached location by changing the location parameter of the OutputCache attribute to any
of the following values: Any, Client, Downstream, Server, None, or ServerAndClient.
By default, the location parameter has the value Any which is appropriate for most the scenarios. But sometimes
there are scenarios when you required more control over the cached data.
Q13. What is Donut caching and Donut hole caching in ASP.NET MVC?
Ans. Donut caching cache an entire web page except for one or more parts of the web page. Before Donut
caching, we have Output Caching which cache the entire web page.
Suppose, you have a web application in which some pages like HomePage, Tools etc. are same for all the users
excepts the user's logged in details like the username.
If you want to cache all these pages for all the users by using OutputCache with VaryByParam UserID, then the
entire page would be cached every time for each user with a different username (or whatever your dynamic part
of the page is). This is not a good practice since there will be 1000 cached pages if there are 1000 logged in user
at a time.
To resolve this issue, Donut Caching was introduced which cached only one copy of the entire page for all the user
except for a small part which remains dynamic. This small part act like as a hole in the cached content and much
like a donut.
Donut caching is very useful in the scenarios where most of the elements in your page are rarely changed except
the few sections that dynamically change, or changed based on a request parameter.
72
Suppose, you have a web application in which ProductCategory is shown on each and every page so it makes sense
to render all of the categories just once and cache the resulting HTML by using Donut Hole Caching.
Donut Hole caching is very useful in the scenarios where most of the elements in your page are dynamic except
the few sections that rarely change, or changed based on a request parameter. ASP.NET MVC has great support
for Donut Hole caching through the use of Child Actions.
73
Page
6
Dependency Injection
Q1. What is loose coupling and how is it possible?
Ans. One of the most important features of the MVC design pattern is that it enables the separation of
concerns. Hence you can make your application’s components independent as much as possible. This is known
as loose coupling, and it makes testing and maintenance of our application easier. Using Dependency Injection,
you can make your application’s components more loosely coupled.
Q2. What are the Dependency Inversion Principle (DIP) and IoC?
Ans. The Dependency Inversion Principle states that:
• High-level modules should not depend upon low-level modules. Both should depend upon abstractions.
• Abstractions should not depend upon details. Details should depend upon abstractions.
The Dependency Inversion Principle (DIP) helps us to develop loosely couple code by ensuring that high-level
modules depend on abstractions rather than concrete implementations of lower-level modules. The Inversion of
Control pattern is an implementation of this principle.
The term Inversion of Control (IoC) refers to a programming style where a framework or runtime, controls the
program flow. Inversion of the control means we are changing the control from normal way. It works on the
Dependency Inversion Principle. The most software developed on the .NET Framework uses IoC.
Moreover IoC is a generic term and it is not limited to DI. Actually, DI and Service Locator patterns are specialized
versions of the IoC pattern or you can say DI and Service Locator are the ways of implementing IoC.
74
Page
For example, suppose your Client class needs to use a Service class component, then the best you can do is to
make your Client class aware of an IService interface rather than a Service class. In this way, you can change the
implementation of the Service class at any time (and for how many times you want) without breaking the host
code.
DIP says High-level module should not depend on the low level module and both should depend on abstraction.
IoC is a way that provides abstraction. A way to change the control. IoC gives some ways to implement DIP. If you
want to make an independent higher level module from the lower level module, then you have to invert the
control so that low-level module does not control interface and creation of the object. Finally, IoC gives some way
to invert the control.
The Dependency Injection pattern uses a builder object to initialize objects and provide the required dependencies
to the object means it allows you to "inject" a dependency from outside the class.
For example, suppose your Client class needs to use a Service class component, then the best you can do is to
make your Client class aware of an IService interface rather than a Service class. In this way, you can change the
75
implementation of the Service class at any time (and for how many times you want) without breaking the host
Page
code.
DI Implementation:
The Service Locator pattern introduces a locator object that objects are used to resolve dependencies means it
allows you to "resolve" a dependency within a class. Above example can be re-written as follows by using SL.
76
Page
public interface IService
{
void Serve();
}
return _Service;
}
}
public Client()
Page
{
this._service = LocateService.GetService();
}
Console.ReadKey();
}
}
• Constructor Injection - This is the most common DI. Dependency Injection is done by supplying the
DEPENDENCY through the class’s constructor when instantiating that class. The injected component can
be used anywhere in the class. Should be used when the injected dependency is required for the class to
function. It addresses the most common scenario where a class requires one or more dependencies.
Console.ReadKey();
}
}
• Property Injection – This is also called Setter injection. This is used when a class has optional
dependencies, or where the implementations may need to be swapped. This is used by different logger
implementations like Log4Net. It may require checking for a provided implementation throughout the
class (need to check for null before using it). It does not require adding or modifying constructors.
set
{
this._service = value;
}
}
Console.ReadKey();
}
}
• Method Injection – This Inject the dependency into a single method, for use by that method only. It could
be useful where the whole class does not need the dependency, just the one method.
this._service = service;
Console.WriteLine("Service Started");
this._service.Serve();
//To Do: Some Stuff
}
}
//Builder
class Program
{
static void Main(string[] args)
{
Client client = new Client();
client.Start(new Service());
Console.ReadKey();
}
}
A DI Container is a framework to create dependencies and inject them automatically when required. It
automatically creates objects based on the request and injects them when required. DI Container helps us to
manage dependencies within the application in a simple and easy way.
We can also manage application dependencies without a DI Container, but it will be like as POOR MAN’S DI and
we have to do more work, to make it configured and manageable.
Castle Windsor
• Understands Decorator
•
Page
Typed factories
• Commercial support available
Spring.NET
• INTERCEPTION
• Comprehensive documentation
• Commercial support available
Autofac
Unity
• INTERCEPTION
• Good documentation
• Consistent API
Ninject
Q10. What are the commonly used tool for Unit Testing in ASP.NET MVC?
Ans. ASP.NET MVC has been designed for testability without dependencies on the IIS server, on a database, or
on external classes. There are following popular tools for ASP.NET MVC testing:
• NUnit - This is the most popular unit testing frameworks for Microsoft .NET. Its syntax is relatively simple
and easy to use. It comes with a test runner GUI and a command-line utility. NUnit is also available as a
NuGet package for download.
• xUnit.NET - This provides a way to run automated unit tests. It is simple, easily extended, and has a very
clean syntax.
• Ninject 2 - This provides a way to wire up classes in your application.
• Moq - This provides a framework for mocking interfaces and classes during testing.
82
Page
References
83
Page