MVC Questions & Answers
In
this article , will discuss about basics of MVC
, so if you are planning for MVC
interview so just go through it , it will help a lot to crack it or add more
technical knowledge about MVC.
1) Explain what is MVC?
MVC is an Acronym of Model View Controller and it is an
Architectural pattern to develop Web Applications.
2) What are the main components of MVC?
There
are three main components of MVC that is Model , View and
Controller so lets take a idea about these
Model
– Model represents business logic where we put our logic like
transformation logic and presentation logic.
View- View is simple User
interface and shows our application look and feel.
Controller – It is main component of MVC that takes request
from the end user and bind view model
view with model and finally send response back to browser.
MVC
also defines application into 3 logical layers
·
Presentation Layers –
showing via View
·
Business Layer –
showing via Model
·
Input Layer -showing via Controller
3) What are Actions?
Action
is the methods or function that is last end point for every request and Every
controller have default action method as Index that is defined in
RouteConfig.cs in route.
4) Explain Advantages of MVC.
MVC have various
advantages but below are two main advantages
·
Separation Of Concern
– It provide an separation of concern means In MVC Code behind is converted to
separate class file and this is achieved through Model , View and controller so
Our UI components does not depend directly to our code behind.
·
Ease of Unit Testing –
As Code behind , has been transferred to a separate class file so that It is
easy to create a unit test as all controller is just a class so we can pass the
appropriate input for Unit testing and get the Response.
·
Now we can maintain out
application easily because of separation of concern
·
In the same time , we
can split work to many developers , it will not affects one developer work to
other.
Routing is a URL mapping mechanism in MVC that decides which action
method of a controller class to executed.
Every incoming request goes
through this process and it is by default in MVC.
To map
routing , First we have to register it in Global.asax.cs via Application_Start
method and then define routes in RouteConfig.cs
as below
public static
void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name:
"Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home", action = "Index", id =
UrlParameter.Optional }
);
}
6) How many return type of Action method available in MVC?
Action
can have many return types as below
·
ViewResult – return
HTML and markup
·
JsonResult - return json
·
EmptyResult -return no
response
·
ContentResult – return
string literal
·
JavaScriptResult
-return javascript script
·
RedirectResult –
redirect to new url or action or controller
·
RedirectToRouteResult –
return to new route defined as per route table
·
PartialViewResult –
return html
·
FileContentResult/FileStreamResult/FilePAthResult
– return content of file
·
HttpUnauthorizedResult
-return HTTP 403 status
7) What is scaffolding?
Scaffolding
is a code generation framework for web application and it generates code for
CRUD operation, It is quite good for new developers and also provides basic
functionality like Login , Register with bootstrap , so developer can easily
learn.
8) Difference between each version of MVC 2, 3 , 4, 5 and 6?
MVC 6
·
ASP.NET MVC and Web API
has been merged in to one.
·
New JSON based project
structure.
·
Side by side - deploy
the runtime and framework with your application
·
Dependency injection is
inbuilt and part of MVC.
·
Everything packaged
with NuGet, Including the .NET runtime itself.
·
No need to recompile
for every change. Just hit save and refresh the browser.
·
Compilation done with
the new Roslyn real-time compiler.
MVC 5
·
Authentication Filters
·
Attribute based routing
·
Asp.Net Identity
·
Bootstrap in the MVC
template
·
Filter overrides
MVC 4
·
ASP.NET Web API
·
New mobile project
template
·
Many new features to
support mobile apps
·
Refreshed and
modernized default project templates
MVC
3
·
Razor
·
JavaScript and Ajax
·
Support for Multiple
View Engines
·
HTML 5 enabled
templates
·
Model Validation
Improvements
MVC 2
·
Templated Helpers
·
Client-Side Validation
·
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
9) Difference between MVC
and three 3 Layered Architecture
·
3 tier divides the
whole app in: UI, logic and data
·
MVC divides the UI part
in: view (kind of UI of the UI), model (data) and controller (logic)
10) How to maintain State in MVC
State can be managed in MVC by
1. Hidden Field
2. Session
3. ViewData
4. ViewBag
5. Session
11) Difference between ViewData and ViewBag?
1.
both are used to send data from Controller to View
2. Usage
In Controller
ViewData[“Data”] =”Test”;
ViewBag.Data = “Test”;
In View
ViewData[“Data”]
ViewBag[“Data”]
3. ViewBag is dyanamic wrapped and
internally use dynamic keyword introduced in C#4.0
4. ViewData needs typecasting in
case of complex type while ViewBag doesn’t need.
12) What is TempData?
·
TempData is
used to send data from Controller to controller or Controller to Action
·
TempData is
used to pass data from the current request to the next request
·
It keeps the
information for the time of an HTTP Request. This means only from one page to
another. It helps to maintain the data when we move from one controller to another
controller or from one action to another action
·
It requires typecasting
for complex data type and checks for null values to avoid error. Generally, it
is used to store only one time messages like the error messages and validation
messages
13) How to maintain TempData request for subsquent Request and what
is keep and peek?
TempData
data is not available for subsequent request if data is read so As per read we
are having two methods one is keep and
usage are
first read then keep
string data= @Html.TempData[“Data”];
@Html.TempData.keep(“Data”);
Peek
also do the same work but it just read the tempdata and also advice to TempData
to provide it for next request as below
String str = @TempData.peek(“Data”).ToString()
14) What are partial Views?
Partial
view is a reusable view like a user
control in web forms 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
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.
15) What is the difference between View and Partial View?
View
·
View is not lightweight
as compare to Partial View.
·
It contains the layout
page.
·
View might have markup
tags like body, html, head, title, meta etc.
·
Before any view is
rendered, viewstart page is rendered.
Partial View:
·
It does not contain the layout page.
·
We can pass a regular
view to the RenderPartial method.
·
Partial view does not
verify for a viewstart.cshtml.We cannot put common code for a partial view
within the viewStart.cshtml.page.
·
Partial view is
designed specially to render within the view and just because of that it does
not consist any mark up.
16) What are Filters in MVC?
In MVC,
controllers define action methods and these action methods generally have a
one-to-one relationship with UI controls such as clicking a button or a link,
etc. For example, in one of our previous examples, the UserController class
contained methods UserAdd, UserDelete, etc.
But
many times we would like to perform some action before or after a particular
operation. For achieving this functionality, ASP.NET MVC provides feature to
add pre and post action behaviors on controller's action methods.
Types of Filter
ASP.NET
MVC
framework supports the following action filters,
Action Filters
Action
filters are used to implement logic that gets executed before and after a
controller action executes. We will look at Action Filters in detail in this
chapter.
Authorization
Filters
Authorization
filters are used to implement authentication and authorization for controller
actions
Result Filters
Result
filters contain logic that is executed before and after a view result is
executed. For example, you might want to modify a view result right before the
view is rendered to the browser.
Exception Filters
Exception
filters are the last type of filter to run. You can use an exception filter to
handle errors raised by either your controller actions or controller action
results. You can also use exception filters to log errors.
Action
filters are one of most commonly used filters to perform additional data
processing, or manipulating the return values or cancelling the execution of
action or modifying the view structure at run time.