MVC - List of Questions
·
Reading
these MVC interview questions does not mean you will go and clear MVC
interviews. The purpose of this article is to quickly brush up your MVC
knowledge before you go for MVC interviews. This article does not teach MVC,
it’s a last minute revision sheet before going for MVC interviews.
If
you want to learn MVC from scratch, start by reading Learn MVC ( Model view
controller) step by step 7 days or you can also start with my step by step MVC (Model View Controller) video series from
YouTube.
If
you want to learn MVC 5 in a short time i.e. 2 days a.k.a 16 hours below is a
video series for the same.
Need help to improve this article
I
have tried my level best to cover what questions i have faced in MVC
interviews. But i feel the below questions are not enough and in real MVC
interview's much more is asked. If you can share your question in the comment
below. I would love to incorporate them in this article so that others are
benefited.
If your question is great and i like it i will ship you a free copy of my .NET interview question book only in India ( sorry i am not so rich for outside countries).
If your question is great and i like it i will ship you a free copy of my .NET interview question book only in India ( sorry i am not so rich for outside countries).
MVC
is an architectural pattern which separates the representation and user
interaction. It’s divided into three broader sections, Model, View, and
Controller. Below is how each one of them handles the task.
·
The View is
responsible for the look and feel.
·
Model represents the
real world object and provides data to the View.
·
The Controller is
responsible for taking the end user request and loading the appropriate Model
and View.
Figure: MVC (Model
view controller)
There
are six broader events which occur in MVC application life cycle below diagrams
summarize it.
Image Courtesy: - http://www.dotnetinterviewquestions.in/article_explain-mvc-application-life-cycle_210.html
Any
web application has two main execution steps first understanding the request
and depending on the type of the request sending out appropriate response. MVC
application life cycle is not different it has two main phases first creating
the request object and second sending our response to the browser.
Creating the request object: -The request object creation has four major steps. Below is the
detail explanation of the same.
Step 1 Fill route: - MVC requests are mapped to route tables which in turn
specify which controller and action to be invoked. So if the request is the
first request the first thing is to fill the route table with routes
collection. This filling of route table happens in the global.asax file.
Step 2 Fetch route: - Depending on the URL sent “UrlRoutingModule” searches the
route table to create “RouteData” object which has the details of which
controller and action to invoke.
Step 3 Request context created: - The “RouteData” object is used to create
the “RequestContext” object.
Step 4 Controller instance created: - This request object is sent to
“MvcHandler” instance to create the controller class instance. Once the
controller class object is created it calls the “Execute” method of the
controller class.
Creating Response object: - This phase has two steps executing the action and finally
sending the response as a result to the view.
The
MVC architecture is suited for a web application than Windows. For Window
applications, MVP, i.e., “Model View Presenter” is more applicable. If you are
using WPF and Silverlight, MVVM is more suitable due to bindings.
There
are two big benefits of MVC:
·
Separation of concerns
is achieved as we are moving the code-behind to a separate class file. By
moving the binding code to a separate class file we can reuse the code to a
great extent.
·
Automated UI testing
is possible because now the behind code (UI interaction code) has moved to a
simple .NET class. This gives us opportunity to write unit tests and automate
manual testing.
MVC
is an evolution of a three layered traditional architecture. Many components of
the three layered architecture are part of MVC. So below is how the mapping
goes:
Functionality
|
Three layered / tiered
architecture
|
Model view controller
architecture
|
Look and Feel
|
User interface
|
View
|
UI logic
|
User interface
|
Controller
|
Business logic
/validations
|
Middle layer
|
Model
|
Request is first
sent to
|
User interface
|
Controller
|
Accessing data
|
Data access layer
|
Data Access Layer
|
Figure: Three layered
architecture
MVC
6 is the latest version which is also termed as ASP VNEXT.
MVC 6
ASP.NET
MVC and Web API has been merged in to one.
Dependency
injection is inbuilt and part of MVC.
Side
by side - deploy the runtime and framework with your application
Everything
packaged with NuGet, Including the .NET runtime itself.
New
JSON based project structure.
No
need to recompile for every change. Just hit save and refresh the browser.
Compilation
done with the new Roslyn real-time compiler.
vNext
is Open Source via the .NET Foundation and is taking public contributions.
vNext
(and Rosyln) also runs on Mono, on both Mac and Linux today.
MVC 5
One
ASP.NET
Attribute
based routing
Asp.Net
Identity
Bootstrap
in the MVC template
Authentication
Filters
Filter
overrides
MVC 4
ASP.NET
Web API
Refreshed
and modernized default project templates
New
mobile project template
Many
new features to support mobile apps
Enhanced
support for asynchronous methods
MVC 3
Razor
Readymade
project templates
HTML
5 enabled templates
Support
for Multiple View Engines
JavaScript
and Ajax
Model
Validation Improvements
MVC 2
Client-Side
Validation
Templated
Helpers
Areas
Asynchronous
Controllers
Html.ValidationSummary
Helper Method
DefaultValueAttribute
in Action-Method Parameters
Binding
Binary Data with Model Binders
DataAnnotations
Attributes
Model-Validator
Providers
New
RequireHttpsAttribute Action Filter
Templated
Helpers
Display
Model-Level Errors
HTML
helpers help you to render HTML controls in the view. For instance if you want
to display a HTML textbox on the view , below is the HTML helper code.
Hide Copy Code
<%= Html.TextBox("LastName") %>
For
checkbox below is the HTML helper code. In this way we have HTML helper methods
for every HTML control that exists.
Hide Copy Code
<%= Html.CheckBox("Married") %>
Both
of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while
“HTML.TextBox” isn’t. Below is a simple HTML code which just creates a simple
textbox with “CustomerCode” as name.
Hide Copy Code
Html.TextBox("CustomerCode")
Below
is “Html.TextBoxFor” code which creates HTML textbox using the property name
‘CustomerCode” from object “m”.
Hide Copy Code
Html.TextBoxFor(m
=> m.CustomerCode)
In
the same way we have for other HTML controls like for checkbox we have
“Html.CheckBox” and “Html.CheckBoxFor”.
Routing
helps you to define a URL structure and map the URL with the controller.
For
instance let’s say we want that when a user types “http://localhost/View/ViewCustomer/”,
it goes to the “Customer” Controller and invokes the DisplayCustomer action.
This is defined by adding an entry in to theroutes collection using the maproute function. Below
is the underlined code which shows how the URL structure and mapping with
controller and action is defined.
Hide Copy Code
routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer",
action = "DisplayCustomer",
id
= UrlParameter.Optional }); // Parameter defaults
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".
Hide Copy Code
public
class HomeController : Controller
{
[Route("Users/about")]
public ActionResult GotoAbout()
{
return View();
}
}
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.
Hide Copy Code
public
class HomeController : Controller
{
[Route("Users/about")]
[Route("Users/WhoareWe")]
[Route("Users/OurTeam")]
[Route("Users/aboutCompany")]
public ActionResult GotoAbout()
{
return View();
}
}
By
using the ActionLink method as shown in the below code. The below code will
create a simple URL which helps to navigate to the “Home” controller and invoke
the GotoHome action.
Hide Copy Code
<%= Html.ActionLink("Home","Gotohome") %>
We
can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP
calls. For instance you can see in the below code snippet the DisplayCustomer action
can only be invoked by HttpGet. If we try to make HTTP POST on DisplayCustomer,
it will throw an error.
Hide Copy Code
[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer
objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}
Sessions
can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.
Figure: Difference
between tempdata, viewdata, and viewbag
·
Temp
data - Helps to
maintain data when you move from one controller to another controller or from
one action to another 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.
Figure: dynamic
keyword
·
Session
variables - By using session
variables we can maintain data from any entity to any entity.
·
Hidden
fields and HTML controls - Helps
to maintain data from UI to controller only. So you can send data from HTML
controls or hidden fields to the controller using POST or GET HTTP methods.
Below
is a summary table which shows the different mechanisms for persistence.
Maintains data between
|
ViewData/ViewBag
|
TempData
|
Hidden fields
|
Session
|
Controller to Controller
|
No
|
Yes
|
No
|
Yes
|
Controller to View
|
Yes
|
No
|
No
|
Yes
|
View to Controller
|
No
|
No
|
Yes
|
Yes
|
“TempData”
maintains data for the complete request while “ViewData” maintains data only
from Controller to the view.
“TempData”
is available through out for the current request and in the subsequent request
it’s available depending on whether “TempData” is read or not.
So
if “TempData” is once read it will not be available in the subsequent request.
Once
“TempData” is read in the current request it’s not available in the subsequent
request. If we want “TempData” to be read and also available in the subsequent
request then after reading we need to call “Keep” method as shown in the code
below.
Hide Copy Code
@TempData[“MyData”];
TempData.Keep(“MyData”);
The
more shortcut way of achieving the same is by using “Peek”. This function helps
to read as well advices MVC to maintain “TempData” for the subsequent request.
Hide Copy Code
string
str = TempData.Peek("Td").ToString();
If
you want to read more in detail you can read from this detailed blog on MVC Peek and Keep.
Partial
view is a reusable view (like a user control) which can be embedded inside
other view. For example let’s say all your pages of your site have a standard
structure with left menu, header, and footer as shown in the image below.
Figure: Partial views
in MVC
For
every page you would like to reuse the left menu, header, and footer controls.
So you can go and create partial views for each of these items and then you
call that partial view in the main view.
When
you add a view to your project you need to check the “Create partial view”
check box.
Figure: Create partial
view
Once
the partial view is created you can then call the partial view in the main view
using theHtml.RenderPartial method
as shown in the below code snippet:
Hide Copy Code
<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>
One
of the easiest ways of doing validation in MVC is by using data annotations.
Data annotations are nothing but attributes which can be applied on model
properties. For example, in the below code snippet we have a simple Customer class with a
property customercode.
This CustomerCode property is
tagged with a Required data annotation attribute. In other words if this model is
not provided customer code, it will not accept it.
Hide Copy Code
public class Customer
{
[Required(ErrorMessage="Customer code is
required")]
public string CustomerCode
{
set;
get;
}
}
In
order to display the validation error message we need to use the ValidateMessageFor method
which belongs to the Html helper class.
Hide Copy Code
<% using (Html.BeginForm("PostCustomer", "Home",
FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m =>
m.CustomerCode)%>
<%=Html.ValidationMessageFor(m
=> m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%>
Later
in the controller we can check if the model is proper or not by using the ModelState.IsValid property
and accordingly we can take actions.
Hide Copy Code
public ActionResult PostCustomer(Customer obj)
{
if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return View("Customer");
}
}
Below
is a simple view of how the error message is displayed on the view.
Figure: Validations in
MVC
Yes,
we can; use the ValidationSummary method from the Html helper class.
Hide Copy Code
<%=
Html.ValidationSummary() %>
What
are the other data annotation attributes for validation in MVC?
If
you want to check string length, you can use StringLength.
Hide Copy Code
[StringLength(160)]
public string FirstName { get; set; }
In
case you want to use a regular expression, you can use the RegularExpression attribute.
Hide Copy Code
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email { get; set; }
If
you want to check whether the numbers are in range, you can use the Range attribute.
Hide Copy Code
[Range(10,25)]public int Age { get; set; }
Sometimes
you would like to compare the value of one field with another field, we can use
the Compareattribute.
Hide Copy Code
public string Password { get; set; }[Compare("Password")]public string ConfirmPass { get; set; }
In
case you want to get a particular error message , you can use the Errors collection.
Hide Copy Code
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;
If
you have created the model object yourself you can explicitly call TryUpdateModel in
your controller to check if the object is valid or not.
Hide Copy Code
TryUpdateModel(NewCustomer);
In
case you want add errors in the controller you can use the AddModelError function.
Hide Copy Code
ModelState.AddModelError("FirstName", "This is my server-side error.");
It’s
a two-step process: first reference the necessary jQuery files.
Hide Copy Code
The
second step is to call the EnableClientValidation method.
Hide Copy Code
<%
Html.EnableClientValidation(); %>
It’s
a light weight view engine. Till MVC we had only one view type, i.e., ASPX.
Razor was introduced in MVC 3.
Razor
is clean, lightweight, and syntaxes are easy as compared to ASPX. For example, in
ASPX to display simple time, we need to write:
Hide Copy Code
<%=DateTime.Now%>
In
Razor, it’s just one line of code:
Hide Copy Code
@DateTime.Now
As
per Microsoft, Razor is more preferred because it’s light weight and has simple
syntaxes.
You
can use Windows or Forms authentication for MVC.
For
Windows authentication you need to modify the web.config file
and set the authentication mode to Windows.
Hide Copy Code
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
Then
in the controller or on the action, you can use the Authorize attribute which
specifies which users have access to these controllers and actions. Below is
the code snippet for that. Now only the users specified in the controller and
action can access it.
Hide Copy Code
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController :
Controller
{
//
// GET: /Start/
[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
public ActionResult Index()
{
return View("MyView");
}
}
Forms
authentication is implemented the same way as in ASP.NET. The first step is to
set the authentication mode equal to Forms. The loginUrl points to a controller here rather than
a page.
Hide Copy Code
<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="2880"/>
</authentication>
We
also need to create a controller where we will check if the user is proper or
not. If the user is proper we will set the cookie value.
Hide Copy Code
public ActionResult Login()
{
if ((Request.Form["txtUserName"] == "Shiv") &&
(Request.Form["txtPassword"] == "Shiv@123"))
{
FormsAuthentication.SetAuthCookie("Shiv",true);
return View("About");
}
else
{
return View("Index");
}
}
All
the other actions need to be attributed with the Authorize attribute so
that any unauthorized user making a call to these controllers will be
redirected to the controller (in this case the controller is “Login”) which
will do the authentication.
Hide Copy Code
[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}
You
can implement AJAX in two ways in MVC:
·
AJAX libraries
·
jQuery
Below
is a simple sample of how to implement AJAX by using the “AJAX” helper library.
In the below code you can see we have a simple form which is created by using
the Ajax.BeginForm syntax.
This form calls a controller action called getCustomer. So now the submit action click will be an
asynchronous AJAX call.
Hide Copy Code
Please do read this
blog which has detailed steps of how model binders can be created using
“IModelBinder” interface: - Explain MVC model Binders?
No comments:
Post a Comment