1) Why we are migrating from ASP.Net to MVC Framework?
Ans:
MVC design
pattern is introduced for to separate the UI (User Interface) from ASP.Net. In normal Application BL (Business Logic),
DL (Data access Layer) and (PL) Presentation Layer all are combining to build
the Applications. So here if you want to do modification for any one of the
layer it’ll effect to all layers. It’s somewhat tedious. Regarding to this
Microsoft has been introduced the MVC Framework/Application in the .Net
Framework.
Model-View-Controller (MVC) has been an
important architectural pattern in computer science for many years. Originally
named Thing-Model-View-Editor in 1979, it was later
simplified to Model-View-Controller.
2)
What is meant by MVC?
Ans: MVC
Means Model View Controller
MVC is a design pattern for software.
It is separation for those layers to manage a complex application. It means it
gives the more flexibility to overall architecture that allows the change to be
made to a layer, without affecting the other layers. It’s providing loose
coupling between these 3 elements (Model, View, and Controller).
The MVC separates the user interface of an application into three main aspects:
M-Model: A set of classes that describe the
data you’re working with as well as the business logic for how the data can be
changing and manipulating. A Model We can call as a Business Logic
(Intermediate for data Exchange between Presentation Logic and Data Access
Layer).
Or
These are the
classes that represent the domain you are interested in. These domain objects
often encapsulate data stored in a database as well as code used to manipulate
the data and enforce domain-specific business logic. With ASP.NET MVC, this is
most likely a Data Access Layer using a some kind of tools like ADO.NET or LINQ
or Entity Framework combined with custom code containing domain-specific logic
or specific domain data.
V-View: Defines how the application’s UI (User Interface) will
be displayed. Its means the view of the user
interface components used to display the Model data. Most of the views are created from the model data.
Or
This is a
template to dynamically generate HTML. When we Creating a View Templates of
Curd Operation or Else.
C-Controller: It handles the user interactions and events.
Controller read data from a view, control user input and send input data to the
model. It manipulates the updates that
model reflect at every change of the state of an application.
Or
This is a special
class that manages the relationship between the View and Model. It responds to
user input, talks to the Model, and it decides which view to render (if any).
In ASP.NET MVC, this class is conventionally denoted by the suffix Controller.
3)
What are the Advantages of MVC Framework?
Or
What are the Benefits Of MVC Framework?
Ans :
Ø MVC Framework is divided in 3
Components as Model (Business Logic), View (Presentation Logic) and Controller
(Input Logic), which helps to Manage Complex Application.
Ø MVC Permitting development, testing
and maitainanace of each.
Ø Its Eliminates the Problem of Load
Time Delays of HTML Markup. Why because of it doesn’t use View State or Server
Side Form. Complete Control over HTML output and html based.
Ø Esaier integration with
Javascript/Jquery.
Ø Building an Internet site where
HTML,Performance,and scalability are paramount ASP.NET MVC3 may be better
suited.
Ø It supports better development of
Test – Driven Development Application (TDD).
Ø Testing Becomes Very Easier and
Individual UI Test also possible.
Ø It Supports ASP.Net Routing which
provides better URL (Universe Resource Locator) Mapping in Our MVC
Applications. In ASP.NET routing URL
can be very useful for Search Engine Optimization (SEO) and Representation
State Transfer (REST).
4)
What are the Versions in MVC Framework?
Ans :
ASP.NET 1.0 was
first released in 2002. , it was easy to think of ASP.NET and Web Forms as one
and the same thing. ASP.NET has always supported two layers of abstraction,
though:
System.Web.UI
: The Web Forms layer, comprising server
controls, View State, & so on
System.Web
: The plumbing, which supplies the basic web
stack, including modules, handlers, the HTTP stack, and so on.
The mainstream
method of developing with ASP.NET included the whole Web Forms stack — taking
advantage of drag-and-drop controls, semi-magical state fullness, and wonderful
server controls while dealing with the complications behind the scenes (an
often confusing page life cycle, less than optimal HTML, and so on).
ASP.NET
MVC was announced in 2007, the MVC pattern was becoming one of the most popular
ways of building web frameworks.
Model-View-Controller (MVC) has been an
important architectural pattern in computer science for many years. Originally
named Thing-Model-View-Editor in 1979, it was later
simplified to Model-View-Controller.
It has been used
in dozens of frameworks since its introduction. You’ll find MVC in Java and
C++, on Mac and on Windows, and inside literally dozens of frameworks.
ASP.NET
MVC 1 Overview:
Even before
the official release, it was clear that ASP.NET MVC wasn’t your standard
Microsoft product. The development cycle was highly interactive: there were nine
preview releases before the official release, unit tests were made available,
and the code shipped under an open source license.
All of these highlighted a philosophy
that placed a high value in community interaction throughout the development
process. The end result was that the official MVC 1.0 release — including code
and unit tests — had already been used and reviewed by the developers who would
be using it. ASP.NET MVC 1.0 was released on 13 March 2009.
ASP.NET
MVC 2 Overview:
ASP.NET
MVC 2 was released just one year later, in March 2010. Some of the main
features in MVC 2 included:
Ø UI
helpers with automatic scaffolding with customizable templates
Ø Attribute-based
Model validation on both client and server
Ø Strongly-typed
HTML helpers
Ø Improved
Visual Studio tooling There were also lots of API enhancements and “pro”
features, based on feedback from developers building a variety of applications
on ASP.NET MVC 1, such as:
Ø Support
for partitioning large applications into areas
Ø Asynchronous
Controllers support
Ø Support
for rendering subsections of a page/site using Html.RenderAction
Ø Lots
of new helper functions, utilities, and API enhancements one important
precedent set by the MVC 2 release was that there were very few breaking
changes. I think this is a testament to the architectural design of ASP.NET
MVC, which allows for a lot of extensibility without requiring core changes.
ASP.NET
MVC 3 Overview:
ASP.NET MVC 3 (generally abbreviated as MVC 3 from now on) shipped just
10 months after MVC 2, driven by the release date for Web Matrix. If MVC 3 came
in a box, it might say something like this on the front:
Ø Expressive Views including the new Razor View
Engine!
Ø NET
4 Data Annotation Support!
Ø Streamlined
validation with improved Model validation!
Ø Powerful hooks with Dependency Resolution and
Global Action Filters!
Ø Rich
JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON
binding!
Ø Now
with NuGet!!!!
Ø For
those who have used previous versions of MVC, we’ll start with a quick look at
some of these major features.
5)
What are the New Features of Asp.Net MVC 3.0?
Ans:
ü
ASP.Net
MVC3 brings you the Razor View Engine (Delimiter @) with Extension of .cshtml
For C# and .vbhrml For VB.
ü An Integrated Scaffolding System
Extensible Via NuGet.
ü HTML5 Enables Project Templates.
ü Powerful hooks With New Dependency
Injection (Provides Loosely Coupling and Easily Testable and Centralize
Configuration) and Global Action filter.
ü Rich JavaScript Support(Including
Unobtrusive JavaScript)
ü JQuery Validation.
ü JSON Binding (JavaScript Object
Notation).
ü Data Annotation support(Validating
the Data for Entity Data Model or LINQ To Sql or Any data like Range attribute,
Required Attribute, Regular Expression Attribute And String Length Attribute
and Etc)
ü HTML Helpers Support HTML5 Style
Attributes.
6)
What is the new Razor View Engine in MVC 3.0 Framework?
Ans:
It
is designed for render the HTML Pages. When we need to include an C# or VB code
with the HTML Markup within Asp.Net web pages then sometimes become very
tedious. To overcome this problem Razor was implemented.
Razor use the semantic parser to use
it within the code block. It works, but it was designed to support editing controls in a
graphical editor, and that legacy shows.
Razor view engine is a new view engine created
with ASP.Net MVC model using specially designed Razor parser to render the HTML
out of dynamic server side code. It allows us to write Compact, Expressive,
Clean and Fluid code with new syntaxes to include server side code in to HTML.
Razor was designed specifically as a View
Engine Syntax. It has one main focus: code-focused for HTML generation.
Extensions of Razor View Engines are
·
.cshtml - If the programming language is C#
·
.vbhtml - If the programming language is VB
7)
What is the Main Function of New Razor View Engine?
Ans:
ü
It
has predefined set of functions that can be used to make the coding more easily
because of Razor doesn’t have the XML Like heavy syntax of the web form view
engine.
ü Razor View Engine is Very Expressive
in writing Style, Compact and Fluid.
ü It provides easy way to integrate the
server code into the HTML Markup.
ü Great IntelliSense (IntelliSense can come in handy for
things like viewing the properties your model object supports).
ü The Razor view
engine’s core compilation engine has no dependencies on System.Web or ASP.NET whatever —
it can be executed from unit tests, or even from the command line, So It Provides the Unit testable.
ü Razor also simplifies
markup with an improvement on the Master Pages concept — called Layouts — that
is both more flexible and requires less code and that became
popular and includes Spark and NHaml.
ü Multiple
views are also popular using a single application or the site as the template
can be viewed using a single engine or more flexibility can be given to the use
of template.
ü Razor
is used as a helper that includes all the helper methods and programming model
features to synchronize with the .ASPX view engine.
ü Razor supports
many local functions with other functionalities that help in block reading and
writing. It also has pre-defined set of functions that can be used to make the
coding more easily.
8)
What
is the Page Life Cycle of an MVC Framework?
Ans:
The mechanism for connecting client-side
events with server-side event handler code, part of the page life cycle, can be
extraordinarily complicated and delicate.
·
APP INITIALIZATION: IF any of the Application is starting from the App_start() in
Global.asax . It means the initiation of the application takes place that allow
the application to interact the server and start to run the application and
create route object in route table collection.
·
Routing: The messages
are routed to the server for making the delivery of the request easier and
provide the URL Mapping.
Routing is a stand-alone
component that matches incoming requests to IHttpHandlers by URL pattern.
MvcHandler is, itself, an IHttpHandler, which acts as a kind of proxy to other
IHttpHandlers configured in the Routes table.
·
Instantiate and Execute Controller: Initialize the request and process and execute to
display output. In this The Active IControllerFactory supplies an IController
Instance. It
basically uses IControllerFactory to identify the controller (Developer can use
different strategy to identify the Controller method and also can create custom
controller by using following Contract /Interface).
Ex : public
interface IController
{
Void Execute(ReuestContext req)
}
·
Locate and Invoke Controller: Controller allows to locating correctly and invokes
the particular action for application. The controller invokes its relevant
action method, which after further processing, Calls RenderView ().The
controller determines which controller method to execute, builds a list of
parameters, and executes the method.
The ControllerActionInvoker object that is
associated with the controller determines which action method of the controller
class to call and then call’s the method. The ControllerActionInvoker gets
created on the basis of the RequestContext object.
·
Instantiate and Render View: The IViewFactory supplies an IView, which pushes
response data to the IHttpResponse object. This helps in view the result of the application
that is being built.
HTTP Request
|
Routing
|
Controller
|
ViewResult
|
ViewEngine
|
View
|
Response
|
9)
Describe
about the ASP.NET MVC Request Life Cycle?
Ans:
Ø
Application
first receives the request & looks up the route object in RouteTable
Collection. Then RouteData Object is created. In ASP.NET MVC application like
normal ASP.NET application when application starts first time, it calls
Application_Start() application event from Global.asax. Route table is
registered(created) from Appication_Start() event.
Ø
The MVCRouteHandler object creates an instance of the
MvcHandler class and passes it the RequestContext object. This is another point
for creating custom handler for the handling the web Request.
Ø
MvcHandler and pass RequestContext to handler is created.
Ø
IControllerFactory from RequestContext is identified.
Ø
IControllerFactory
from RequestContext is identified.
Ø
The object of class that implements ControllerBase is
created.
Ø
In MyController Excute method is created.
Ø
The ControllerActionInvoker finds the action to invoke on
the controller and executes that action on the controller and return to the
view.
10)
How
Asp.Net MVC differs from Asp.Net WebForms?
Or
What is
the difference between ASP.NET MVC and ASP.NET WebForms ?
Ans:
ASP.NET MVC is not a replacement for ASP.NET WebForms. Both ASP.NET MVC and ASP.NET WebForms are built on top
of the Core ASP.NET Framework. In fact a lot of features we use in ASP.NET such
as Roles, Membership, Authentication and a lot of namespaces, classes and
interfaces can be used in an ASP.NET MVC application.
Asp.net framework is a part of .net platform for
building, deploying and running web applications. Now, we can develop a web
application by using Asp.Net Web Form and Asp.Net MVC.
ASP.NET WebForms
|
ASP.NET MVC
|
Asp.Net WebForm Follow a traditional event driven development
model
|
Asp.net MVC is a lightweight and
follow MVC pattern based development model
|
Asp.Net Web Form has User Controls for code re-usability
and is not open source.
|
Asp.Net MVC has Partial Views for code re-usability and
is an open source.
|
Uses the ‘Page Controller’ pattern. Each page has a
code-behind class that acts as a controller and is responsible for rendering
the layout.
|
Uses the ‘Front Controller’ pattern. There is a single
central controller for all pages to process web application requests and
facilitates a rich routing architecture
|
Uses an architecture that combines the Controller (code
behind) and the View (.aspx). Thus the Controller has a dependency on the
View. Due to this, testing and maintainability becomes an issue.
|
ASP.NET MVC enforces a "separation of concerns".
The Model does not know anything about the View. The View does not know
there’s a Controller. This makes MVC applications easier to test and maintain
|
The View is called before the Controller.
|
Controller renders View based on actions as a result of
the User Interactions on the UI.
|
At its core, you ‘cannot’ test your controller without
instantiating a View. There are ways to get around it using tools.
|
At its core, ASP.NET MVC was designed to make test-driven
development easier. You ‘can’ test your Controller without instantiating a
View and carry out unit-tests without having to run the controllers in an
ASP.NET process.
|
Asp.Net Web Form has server controls and WebForms manage state by using view state and server-based
controls.
|
Asp.Net MVC has html helpers and ASP.NET MVC does not maintain state information by using
view state
|
Asp.Net Web Form has file-based URLs means file name
exist in the URLs must have its
physically existence
|
Asp.Net MVC has route-based URLs means URLs are divided
into controllers and actions and moreover it is based on controller not on
physical file.
|
WebForms supports an event-driven programming style that
is like Windows applications and is abstracted from the user. The State
management is made transparent by using sessions, viewstate etc. In the
process, the HTML output is not clean making it difficult to manage later.
The ViewState also increases your page size.
|
In ASP.NET MVC, the output is clean and you have full
control over the rendered HTML. The orientation is towards building standard
compliant pages and provides full control over the behavior of an
application.
|
Deep understanding of HTML, CSS and JavaScript is not
required to a large extent since the WebForm model abstracts a lot of these
details and provides automatic plumbing. While abstracting details to provide
ease of use, sometimes a solution is overcomplicated, than it needs to be.
|
A thorough understanding of how HTML, CSS and JavaScript
work together is required. The advantage is you can do a lot of jQuery and
AJAX stuff in an efficient and simple manner than you would do in an ASP.NET
application.
|
WebForms can drastically reduce time while building up
intranet and internet applications that use a lot of controls (drag and drop
model). Although this is true for development, a lot of time is spent later
to code around limitations.
|
You lose the 'drag and drop' quick model of building your
web applications. The focus is on control over the application behavior and
test-driven development. The model is extensible and you do not have to spend
time working around limitations.
|
Relatively simple to learn and pickup. Works very well for
developers who initially have trouble with the HTTP/HTML model and are coming
from a similar WinForms oriented event model.
|
There is a learning curve to understand the why, when and
how of ASP.NET MVC.
|
Lesser amount of code is required to build webapps since a
lot of components are integrated and provided out of the box. You can also
use a lot of data controls provided out of the box that rely on ViewState.
|
Since the application tasks are separated into different
components, amount of code required is more. Since ASP.NET MVC does not use
ViewState, you cannot use Data controls like GridView, Repeater.
|
Works very well for small teams where focus is on rapid
application development.
|
Works well for large projects where focus in on
testability and maintainability.
|
11)
How
Asp.Net MVC Framework differs from others?
Ans:
Ø
Asp.Net MVC uses a complete Model-View-Controller
Architecture that combines the Controller and thye view in a way that both
meets the dependency of each other and provides loose coupling between these 3
elements.
Ø
In many Web
Frameworks such as ASP,JSP,PHP and ASP.NET,The URL represents a Physical file
on disk.In MVC doesn’t necessarily mean a physical location of a static file on
a web server’s hard drive somewhere; it mose certainly doesn’t in the case of
ASP.NET MVC.
Ø
The testing
of the architecture can be done by instantiating a View and carrying out the
unit tests without running the controller through the complete cycle.
Ø The Control of MVC on the output is complete and it renders the HTML in a very clean way and it controls the delay of page load.
Ø The Control of MVC on the output is complete and it renders the HTML in a very clean way and it controls the delay of page load.
Ø
In MVc the
Scaffolding Templates Curd Operation is full worthy component based in MVC
Framework,but JSP is a barebones view technology & Servlet is just a
barebones HTTP Controller API and Comparison of Scaffloding plug-in in JSF.
Ø The MVc Architecture Provides an orientation towards the standard complaint pages and control over the behavior of the applications
Ø the knowledge of many programming language gets reduced and the model can become more abstract from lots of details that is provided for the ease of use.
Ø MVC is not a language for frontend and backend with a language like PHP or C#/VB.Net and to get parsed by the Server(PHP,C#/VB) and a languages markups get parsed by the client browsers(JavaScript/JQuery/HTML/CSS) and you can Mix the two and Parse to Server.So it’s the open source for .Net.
Ø The MVc Architecture Provides an orientation towards the standard complaint pages and control over the behavior of the applications
Ø the knowledge of many programming language gets reduced and the model can become more abstract from lots of details that is provided for the ease of use.
Ø MVC is not a language for frontend and backend with a language like PHP or C#/VB.Net and to get parsed by the Server(PHP,C#/VB) and a languages markups get parsed by the client browsers(JavaScript/JQuery/HTML/CSS) and you can Mix the two and Parse to Server.So it’s the open source for .Net.
12)
Explain
the ASP.NET MVC Folder Conventions?
Ans:
Folder or File
Description Notes
/App_Data
This
directory is where you put private
IIS will not serve the contents of
data, such as
XML files or databases this
directory.
if you are using SQL Server
Express,
SQLite, or
other file-based repositories.
/bin The compiled
assembly for your MVC IIS will not
serve the contents of
application
is placed here,along with this
directory. You won’t see the
any
referenced assemblies that are
bin directory in the solution
not in the
GAC.
explorer window unless you click
the Shows
all Files button. these are
binary files generated on compilation,
you should not normally
store them
in source control.
/Content
This
is where you put static content This
is a convention but not required.
such as CSS
files and images. You
can put your static content
anywhere that suits you.
/Controllers
This
is where you put your controller
This is a convention. You can put your
classes.
controller classes anywhere you like,
because
they are all compiled into the
same assembly.
/Models
This
is where you put your view
This is a convention. You can define
model and domain model classes, your model classes anywhere in the
although all but the simplest appl project or in a separate project.
benefit from defining the domain
model in a dedicated project, as we
demonstrated for Sports Store.
/Scripts
This
directory is intended to hold the
This is a convention. You can put script
JavaScript libraries for your appl. files in any location, as they
are really
Visual Studio adds the libraries for just another type of static
content.
jQuery and Microsoft AJAX helpers by default.
/Views This directory
holds views and partial The /Views/Web.config
file
prevents IIS
Views, usually grouped together in from serving the content of these
Folders named after the controller directories. Views must be
rendered
With which they are associated.
13)
Explain
the Namespace Classes used in ASP.Net MVC?
Ans:
Asp.Net MVC uses the
namespace classes that as follows
System.Web.Mvc
namespace
Contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders.
System.Web.Mvc.Ajax namespace
Contains classes that support Ajax scripts in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings.
System.Web.Mvc.Async namespace
Contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application. The Goal of the asynchronous Classes in controllers to provide better scalability, especially for complex calculations that take long which are accessed by many simultaneous users.
System.Web.Mvc.Html namespace
Contains classes that help render HTML controls in an MVC application. The namespace includes classes that support forms, input controls, links, partial views, and validation.
Contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders.
System.Web.Mvc.Ajax namespace
Contains classes that support Ajax scripts in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings.
System.Web.Mvc.Async namespace
Contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application. The Goal of the asynchronous Classes in controllers to provide better scalability, especially for complex calculations that take long which are accessed by many simultaneous users.
System.Web.Mvc.Html namespace
Contains classes that help render HTML controls in an MVC application. The namespace includes classes that support forms, input controls, links, partial views, and validation.
Every Views inherits an Html property from its base class. All of
MVC’s extension methods for
HtmlHelper live in the System.Web.Mvc.Html namespace.
14)
Can
you add the own Namespaces in ASP.Net MVC and How?
Ans:
Yes, You can add your own namespaces i.e Custom Namespaces and Look Like this
<add namespace="My.Custom"/>
So it'll add the namespace to all of .Cshtml in C# and .Vbhtml in VB files and also you can chnage Views and you can access for only one view look like this
<pages pageBaseType = "My.Custom.MVCWebPage />
Yes, You can add your own namespaces i.e Custom Namespaces and Look Like this
<add namespace="My.Custom"/>
So it'll add the namespace to all of .Cshtml in C# and .Vbhtml in VB files and also you can chnage Views and you can access for only one view look like this
<pages pageBaseType = "My.Custom.MVCWebPage />
For Example:
<pages pageBaseType= “System.Web.Mvc.WebViewPage”>
<namespaces>
<add namespace=”MyCustomNamespace”/>
</namespaces>
<pages>
15) What are the return type’s controller
action methods supports in ASP.NET MVC?
Ans:
There are total nine return types we can use to
return results from controller to view. The base type of all these result types
is ActionResult.
Controller Convenience Methods That Return ActionResult
Instances
1.
RedirectResult (Redirect): Used to redirect to
another controller and action method based on a URL and return appropriate URL.
2.
RedirectToRouteResult(RedirectToAction): Returns a RedirectToRouteResult, which
redirects the user to an action using the supplied route values.
3.
RedirectToRouteResult (RedirectToRoute): Returns a RedirectToRouteResult, which
redirects the user to the URL that matches the specified route values.
4.
ViewResult (View): Returns a ViewResult, which
renders the View to the response. Used to return a webpage from an action method.
5.
PartialviewResult(PartialView): Returns a PartialViewResult, which
renders a partial View to the response. Used to send a section of a view to be
rendered inside another view.
6.
ContentResult (Content): Returns a ContentResult, which
writes the specified content (string) to the response. It means used to
return a custom content type as the result of the action method. This is an
HTTP content type, such as text/plain.
7.
FileResult (File): Returns a
class that derives from FileResult, which writes binary content to the response.
8.
JsonResult (Json): Returns a JsonResult containing
the output from serializing an object to JSON. It means used to return a message
formatted as JSON.
9.
JavascriptResult (Javascript): Returns a JavaScriptResult
containing
JavaScript code that is immediately executed when returned to the client. It
means used
to return JavaScript code that will be executed.
16) How to create an Action method in
Asp.Net MVC?
Ans:
Add a simple method inside a Controller class with ActionResult return type.
Add a simple method inside a Controller class with ActionResult return type.
17) What is the default Form Method (i.e.
Get or Post) for an Action method in Asp.Net MVC?
Ans:
GET. To
change this you can add an action level attributes e.g(HttpPost)
18) What are the return type’s
controller action results types to perform the methods in ASP.NET MVC?
Ans:
ACTIONRESULT TYPE
|
DESCRIPTION
|
ContentResult
|
Writes the specified content directly to the response as
text.
|
EmptyResult
|
Represents a null or empty response. It doesn’t do anything.
|
FileContentResult
|
Derives from FileResult and writes
a byte array to the response.
|
FilePathResult
|
Derives from FileResult and writes
a file to the response based on a file path.
|
FileResult
|
Serves as the base class for a set of results that
writes a binary response to the stream. Useful for returning files to the
user.
|
FileStreamResult
|
Derives from FileResult and writes
a stream to the response.
|
HttpNotFound
|
Derives from HttpStatusCodeResult. Returns
an HTTP 404 response code to the client, indicating that the requested
resource is not found.
|
HttpStatusCodeResult
|
Returns a user-specifi ed HTTP code
|
HttpUnauthorizedResult
|
Derives from HttpStatusCodeResult. Returns
an HTTP 401 response code to the client, indicating that the requestor does
not have authorization to the resource at the requested URL.
|
JavaScriptResult
|
Used to execute JavaScript code immediately on the
client sent from the server.
|
JsonResult
|
Serializes the objects it is given into JSON and writes
the JSON to the response, typically in response to an Ajax request.
|
PartialViewResult
|
This is similar to ViewResult, except it
renders a partial View to the response, typically in response to an Ajax
request.
|
RedirectResult
|
Redirects the requestor to another URL by returning
either a temporary redirect code 302 or permanent redirect code 301 depending
upon a Boolean Permanent flag.
|
RedirectToRouteResult
|
Similar to RedirectResult, but
redirects the user to a URL specified via Routing parameters.
|
ViewResult
|
Calls into a View engine to render a View to the
response.
|
19) What is Action Filters in Asp.Net MVC?
Ans:
Action filters
(locating and injecting filters)
It’s applied for pre and or processing logic to
controller action. Its uses to cross putting logic to your application.
MVC
Action filters gave you hooks to execute code before or after an action method
ran. They were implemented as custom attributes that could be applied to
controller actions or to an entire controller. This is especially useful for
application infrastructure concerns like error handling and logging.
Once an action method has been selected, the
action is then executed, and if it returned a result, the result is then
executed. Action filters allow the developer to participate in the action and
result execution pipeline in four ways: for authorization, for pre- and
post-processing of actions, for pre- and post-processing of results, and for
error handling.
Action filters can be written as attributes
that are applied directly to the action methods (or controller classes), or as
standalone classes that are registered in the global filter list. If you intend
to use your action filter as an attribute, it must derive from FilterAttribute
(or any
subclass, such as ActionFilterAttribute). A global action filter that is not an attribute
has no base class requirements. Regardless of which route you take, the
filtering activities you support are determined by the interfaces you
implement.
20) Describe the different types of Action
Filters in ASP.NET MVC?
Ans:
There are mainly three types of action filters
provided in ASP.NET MVC.
Authorization Filter: It makes security
decisions about whether to execute an action method, such as performing
authentication or validating properties of the request. Authorization filters
execute very early in the action pipeline, so they’re appropriately.
It is used for activities that short circuit
the entire action execution. TheAuthorizeAttribute class is one example of an
authorization filter.
Action and Result Filter: An action filter that wants to participate in pre- and post-processing of actions should implement the IActionFilter interface. This interface offers two methods to implement: OnActionExecuting(for pre-processing) and OnActionExecuted (for post-processing). Similarly, for pre- and post processing of results, an action filter should implement IResultFilter, with its two filter methods:OnResultExecuting and OnResultExecuted.
It wraps execution of the ActionResult object.
This filter can perform additional processing of the result, such as modifying
the HTTP response. TheOutputCacheAttribute class is one example of a result
filter.
Execution Filter: It executes if there is an unhandled exception thrown somewhere in action method, starting with the authorization filters and ending with the execution of the result. Exception filters can be used for tasks such as logging or displaying an error page. The HandleErrorAttribute class is one example of an exception filter.
Apart from the readymade action filters
provided by ASP.NET MVC, you can also implement your own action filter by
inheriting ActionFilterAttribute abstract class. It has four virtual methods
that you can override: OnActionExecuting, OnActionExecuted, OnResultExecuting
and OnResultExecuted. To implement an action filter, you must override at least
one of these methods.
Developers often use exception filters to
perform some sort of logging of the errors, notification of the system
administrators, and choosing how to handle the error from the end user’s
perspective (usually by sending the user to an error page)
21) Give an Example for Authorization Filtes in an Asp.Net MVC Application ?
Ans:
1. ReuireHttpsAttribute
2. AuthorizeAttribute
1. ReuireHttpsAttribute
2. AuthorizeAttribute
22 Give an Example for Result Filters in an Asp.Net MVC Application ?
Ans:
OutputCacheAttribute
OutputCacheAttribute
23 Which Filters Excutes First in an Asp.Net MVC Application ?
Ans:
Authorization filter
Authorization filter
24 Which filters are executed in the end ?
Ans:
Exception Filters
Exception Filters
25) What are The HTML Helpers in ASP.NET
MVC?
Ans:
Every Razor view
inherits an Html
property
from its base class. The Html property is of type System.Web.Mvc.HtmlHelper.
In MVC, HTML Helpers are much like
traditional ASP.NET web form controls. Just like web form controls in ASP.NET,
HTML helpers are used to modify HTML. But HTML helpers are more lightweight.
Unlike Web Form controls, an HTML helper does not have an event model and a
view state. In most cases, an HTML helper is just a method that returns a
string. With MVC, you can create your own helpers, or use the built in HTML
helpers. MVC includes standard
helpers for the most common types of HTML elements, like HTML links and HTML
form elements.To name a few there is BeginForm(), EndForm(), TextBox(),
TextArea(), ListBox(), RadioButton(), etc.
Detailed Description:
The MVC Templated HTML Helpers
Helper
|
Example
|
Description
|
Display
|
Html.Display("FirstName")
|
Renders a read-only view of the specified model property,
choosing an HTML element according to the property’s type and metadata
|
DisplayFor
|
Html.DisplayFor(x =>x.FirstName)
|
Strongly typed version of the previous helper
|
Editor
|
Html.Editor("FirstName")
|
Renders an editor for the specified model property, choosing
an HTML element according to the property’s type and metadata
|
EditorFor
|
Html.EditorFor(x =>x.FirstName)
|
Strongly typed version of the previous helper
|
Label
|
Html.Label("FirstName")
|
Renders an HTML <label> element
referring to the specified model property
|
LabelFor
|
Html.LabelFor(x => x.FirstName)
|
Strongly typed version of the previous helper
|
DisplayText
|
Html.DisplayText("FirstName")
|
Bypasses all templates and renders a simple string representation
of the specified model property
|
DisplayTextFor
|
Html.DisplayTextFor(x =>
x.FirstName)
|
Strongly typed version of the previous helper
|
The MVC Scoffolding Templated HTML Helpers
Helper
|
Example
|
Description
|
DisplayModelFor
|
Html.DisplayModelFor ()
|
Renders a read-only view of the entire model object
|
EditorForModel
|
Html.EditorForModel()
|
Renders editor elements for the entire model object
|
LabelForModel
|
Html.LabelForModel()
|
Renders an HTML <label> element
referring to the entire model object
|
26) What is Routing?
Ans:
A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in our web application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.
A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in our web application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.
When you create a new ASP.NET MVC application, the
application is already configured to use ASP.NET Routing. ASP.NET Routing is
setup in two places.
First,
ASP.NET Routing is enabled in your application's Web configuration file
(Web.config file). There are four sections in the configuration file that are
relevant to routing:
1)
the system.web.httpModules section,
2)
the
system.web.httpHandlers section,
3)
the
system.webserver.modules section, and
4)
the
system.webserver.handlers section.
Be careful not to delete these sections because
without these sections routing will no longer work.
Second,
and more importantly, a route table is created in the application's Global.asax
file. The Global.asax file is a special file that contains event handlers for
ASP.NET application lifecycle events. The route table is created during the
Application Start event.
27)
How
you define the routing system and describe?
Ans:
Every ASP.NET MVC application needs at least one route to define how the application should handle requests but usually will end up with a handful or more. It’s conceivable that a very complex application could have dozens of routes or more.
Every ASP.NET MVC application needs at least one route to define how the application should handle requests but usually will end up with a handful or more. It’s conceivable that a very complex application could have dozens of routes or more.
You’ll see how to define routes Route
definitions start with the URL pattern, which specifies the pattern that the
route will match. Along with the route URL, routes can also specify default
values and constraints for the various parts of the URL, providing tight
control over how and when the route matches incoming request URLs. Routes can
also have names which are associated with the route when that route is added to
a route collection. We’ll cover named routes a bit later.
Ex :
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(“JaganContoller”,
“{first}/{second}/{third}”);
}
public static void RegisterRoutes(RouteCollection
routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with
parameters
new { controller = "MVC",
action = "ListOfQuestions", id =
UrlParameter.Optional }
);
The ASP.NET routing system is used by MVC to handle incoming requests from clients, but it
also requests outgoing URLs that conform
to our URL scheme and that we can embed in web pages. This way, we make sure
that all of the URLs in the application are consistent.
Generate outgoing URLs. These are the URLs that appear in the
HTML rendered
from our views so that a specific action will be invoked when
the user clicks the
link (at which point, it has become an incoming URL again).
we will focus on defining routes and using them to process incoming
URLs so that the user can reach your controllers and actions.
Then we’ll show you how to use those same routes to generate the outgoing URLs
you will need to include in your HTML.
28) How route table is created in asp.net mvc?
Ans:
When an MVC Application first start, The Application_start() method is
called.This method,in turn, calls the RegisterRoutes() method.The
RegisterRoutes() method creates the route table object in route table
collection.
29 What is the difference between adding routes, to a webform application and to an MVC application ?
Ans:
To add routes to a webform application, we use MapPageRoute() method of
the RouteCollection class, where as to add routes to an MVC
appilication we use MapRoute method().
30) What are the 3 things that are needed to
specify name?
Ans:
1. URL Pattern - You can include
placeholders in a URL pattern so that variable data can be passed to the request
handler without requiring a query string.
2. Handler - The handler can be a physical file such as an .aspx file or a
controller class.
3. Name for the Route - Name is optional.
31) What are 3 segments of the default route, which is present in an ASP.NET MVC application?
Ans:
1st Segment - Controller
Name(Route Name)
2nd Segment - Action Method Name
3rd Segment - Parameter that is passed to the action method
2nd Segment - Action Method Name
3rd Segment - Parameter that is passed to the action method
routes.MapRoute(
"Default",
// Route name
"{controller}/{action}/{id}", // URL with parameters
new
{ controller = "Home", action = "Index", id = UrlParameter.Optional
} // Parameter defaults );
32) What is the
use of the following default
route?
Ans:
{resource}.axd/{*pathInfo}
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.
33) Where the
routing rules are defined in an asp.net MVC application?
Ans:
When
application start,The Appilication_start event occurred and RegisterRoutes value
will be defined
in Global.aspx
34) Is the
following route definition a valid route definition?
Ans:
{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.
No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.
35) How do you
handle variable number of segments in a route definition?
Ans:
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.
controller/{action}/{*parametervalues}
controller/{action}/{*parametervalues}
36) What are the
2 ways of adding constraints to a route?
Ans:
1. Use regular
expressions
2. Use an
object that implements IRouteConstraint interface
37) Give 2
examples for scenarios when routing is not applied?
Ans:
1. A Physical
File is Found that Matches the URL Pattern -
This default behaviour can be overriden by setting the RouteExistingFiles
property of the RouteCollection object to true.
2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.
2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.
38) What is Data Annotations?
Ans:
The MVC
Framework can perform client-side validation based on the data annotations we
applied to the domain model class.
Data Annotations are validation mechanism we can use to validate our
data stored in form of Entity Data Model, LINQ to SQL or any other data models.
We can use it in form of attributes to our properties of mode class. These
attributes provide common validation patterns, such as range checking and
required fields. Once we apply these attributes to our model class, ASP.NET MVC
will provide both client and server side validation checks with no additional
coding required. You can also implement your custom Data Annotation Validator
by inheriting ValidationAttribute class and overriding IsValid method. To name
a few there is RangeAttribute, RequiredAttribute, StringLengthAttribute,
RegularExpressionAttribute, etc.
The core library provides server-side validation attributes
that can be used in any .NET 4.0 project (no MVC dependency). There is also an
easily pluggable client-side validation library which can be used in ASP.NET
MVC 3 projects using unobtrusive jquery validation (only MVC3 included
javascript files are required).
Validation
of user input is integral to building a modern web application, and ASP.NET MVC
offers us a way to enforce business rules on both the client and server using
Model Validation. The recent release of ASP.NET MVC 3 has improved these offerings
on the client side by introducing an unobtrusive validation library built on
top of jquery.validation. Out of thebox MVC comes with support for Data
Annotations (that is, system.ComponentModel. DataAnnotations) and can be
extended to support other frameworks. Data Annotations Validation is
becoming more popular and is being baked in to many other Microsoft offerings,
including Entity Framework, though with MVC it only contains four validators: Range, Required, StringLength and Regular Expression. The
Data Annotations Extensions project attempts to augment these validators with
additional attributes while maintaining the clean integration Data Annotations
provides.
39) Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?
Ans:
Yes, it is possible to combine ASP.NET webforms
and ASP.MVC and develop a single webapplication.
40) Which approach provides better support for test driven
development - ASP.NET MVC
or ASP.NET Webforms?
Ans:
ASP.NET MVC
41) Is it possible to unit test an MVC application without running the controllers in an
ASP.NET process?
Ans:
Yes, all the features in an asp.net MVC application are interface based and hence mocking
is much easier. So, we don't have to run the controllers in an ASP.NET process
for unit testing.
42) Is it possible to share a view across multiple controllers?
Ans:
Yes,
put the view into the shared folder. This will automatically make the view
available across multiple controllers.
43) What is the significance of NonActionAttribute?
Ans:
In
general, all public methods of a controller class are treated as action
methods. If you want prevent this default behaviour, just decorate the public
method with NonActionAttribute.
44) What symbol
would you use to denote, the start of a code block in razor views?
Ans:
@
45) What symbol
would you use to denote, the start of a code block in aspx views?
Ans:
<%=%>
46) In razor syntax, what is the escape sequence character for @ symbol?
Ans:
The escape
sequence character for @ symbol, is another @ symbol
47) When using razor views, do you have to take any special steps to protect
your asp.net mvc application from cross site scripting (XSS) attacks?
Ans:
No, by default content emitted using a @ block is
automatically HTML encoded to protect from cross site scripting (XSS) attacks.
48) When using
aspx view engine, to have a consistent look and feel, across all pages of the
application, we can make use of asp.net master pages. What is asp.net master
pages equivalent, when using razor views?
Ans:
To have a consistent look and feel when using razor views, we
can make use of layout pages. Layout pages, reside in the shared folder, and
are named as _Layout.cshtml.
49) How do you specify comments using razor syntax?
Ans:
Razor syntax makes use of @* to indicate the begining of a
comment and *@ to indicate the end. An example is shown below.
50) What are sections?
Ans:
Layout pages, can define sections, which can then be
overriden by specific views making use of the layout. Defining and overriding
sections is optional.
51) What is Repository Pattern in ASP.Net MVC?
Ans:
The Repository will delegate to the appropriate
infrastructure services to get the job done.It uses mechanism of encapsulating that storage, retrieval
& query for the implementation of the repository.
It allows easy testing in the form of unit
testing & mock testing.
Repository
pattern is used as a default entity operation that allows the decoupling of the
components used for presentation.
Repository
pattern will have the proper infrastructure services to be used in the web applications.
Repository
patterns are hard coded in the application that is to be used in ASP.NET MVC
architecture.
52) What is difference between TempDate and ViewData and ViewBag Pattern in
ASP.Net MVC?
Ans:
TempData :
·
TempData is also a dictionary derived
from TempDataDictionary class and stored in short lives session and it is a
string key and object value.
·
TempData keep the information for
the time of an HTTP Request. This mean only from one page to another.
·
It requires typecasting for complex
data type and check for null values to avoid error. It’s used to store one time messages like
error messages,validation messages.
·
Helps to maintain data when you move
from one controller to other controller or from one action to other action. In
other words when you redirect, “Tempdata” helps to maintain data between those
redirects. It internally uses session
variables.
·
It’s life is very short and lies
only till the target view is fully loaded.
ViewData :
·
ViewData is a dictionary object that you put data into, which
then becomes available to the view.
·
ViewData is a derivative of
the ViewDataDictionary class, so you can access by the familiar
"key/value" syntax.
·
ViewData is used to pass
data from controller to corresponding view.
·
Its required typecasting for
complex data type and check for null values to void error.
·
Its life lies only during
the current request.
·
If redirection occurs then
it’s value becomes null.
·
Helps to
maintain data when you move from controller to view.
ViewBag
:
·
ViewBag is a
dynamic property that takes advantage of the new dynamic features in C# 4.0.
·
ViewBag
doesn’t require typecasting for complex data type.
·
Viewbag
is used to pass data from controller to
corresponding view.
·
Helps
to maintain data when you move from controller to view.
·
It’s life aslo
lies only during the current request.
Note : TempData need more verification to never have
any confidential information. Regarding ViewData or ViewBag you should use it
intelligently for application performance. Because each action goes through the
whole life cycle of regular asp.net mvc request. You can use ViewData/ViewBag
in your child action but be careful that you are not using it to populate the
unrelated data which can pollute your controller.
ViewData VS ViewBag VS TempData
ViewData
|
ViewBag
|
TempData
|
It is
Key-Value Dictionary collection
|
It is a type
object
|
It is
Key-Value Dictionary collection
|
ViewData is a
dictionary object and it is property of ControllerBase class
|
ViewBag is
Dynamic property of ControllerBase class.
|
TempData is a
dictionary object and it is property of controllerBase class.
|
ViewData is
Faster than ViewBag
|
ViewBag is
slower than ViewData
|
NA
|
ViewData is
introduced in MVC 1.0 and available in MVC 1.0 and above
|
ViewBag is
introduced in MVC 3.0 and available in MVC 3.0 and above
|
TempData is
also introduced in MVC1.0 and available in MVC 1.0 and above.
|
ViewData
is also work with .net framework 3.5 and above
|
ViewBag
is only work with .net framework 4.0 and above
|
TempData
is also work with .net framework 3.5 and above
|
Type
Conversion code is required while enumerating
|
In depth,
ViewBag is used dynamic, so there is no need to type conversion while
enumerating.
|
Type
Conversion code is required while enumerating
|
It value
become null if redirection is occurred.
|
Same as
ViewData
|
TempData is
used to pass data between two consecutive requests.
|
It lies only
during the current request.
|
Same as
ViewData
|
TempData is
only work during the current and subsequent request
|
53) What are the areas in mvc?
Ans:
Controllers should
only be responsible for interacting with views. That is, instantiating and
populating model objects, retrieving data from your business objects or data
access layer, responding to any requests from the page (form submissions, AJAX
requests, interface to dynamic resource creation methods/classes (such as
creating CAPTCHAs or other dynamic images)), etc. If you stick to that
philosophy, their size and complexity should never exceed that of your views.
Areas I tend to use areas to break up the application into
sub-applications. For instance, a site may have a discussion forum, Employee
Category, Department Category, Company information, support database, etc, all
of which would be separate areas:
/areas/Employee
/areas/Department
/areas/Support
/areas/CompanyInfo
Then, in each area,U
might have some methods
/areas/Employee/{Views|Controllers}
/areas/Employee/EmployeeList
/areas/Employee/EmployeeContactList
etc
Just as in a webforms
site where each folder represented a distinct "area" of the website,
areas provide another level of organization that lets you keep related
controllers, views, etc in a common location, and should be used in a similar
fashion.
We use areas to distinguish notable separate concerns within the application.
Especially separate concerns that may require unique authentication or
layout/styling for each area.
For example, I'm working on an application that has
"modules" of sorts. Each module is an mvc area and each module as a
setup section that is also an mvc area. The application has three modules, so
that is a total of six areas -- with six user rights to go along with them.
This allows each module to have a new "master page/layout"
(appearance) and a specific security level.
It helps in
separating the code as well; code in Areas has nothing to do with code in
AreaB, but sometimes AreaA and AreaB use common code found in the root of the
project.
The non-area parts of the site have things like the
user-login, error pages (404, etc), the main "launcher" area to enter
the modules, exception handing, and other encompassing things that cross-cut
across any of the mvc areas.
54) Whether Razor Views are Precompiled Or not ? and What is the use
of precomilation of Views?
Ans:
By Default, the operating of Comiling a Razor view is close enough to that
used by WebForms Views.This Means that processes and compiles the views of an
ASP.NET MVC Application as late as possible,it is called JIT(Just In Time).As late as
possible" meaning when a reply using the view in question must be returned
to a client. Once this stage of
compilation is complete, the result is cached in the temporary directory of the
IIS site, and future clients accessing this resource will not cause a new
compilation.
Obviously, the time of compilation of views
will now be passed on to the position of each developer on the team. A hybrid solution would be to compile
the views, nor at runtime or on the position of each developer, but during the
compilation process of continuous integration.
One Reason used by precompilation than at
runtime compilation.You no longer need to deploy the cshtml views at all.and
ability to unti test your views ,which has always been something very difficult
with standard runtime compilation model.
55) What is Globalization and
Internationalization and Localization in ASP.NET MVC3 ?
Ans:
Internationalization : Making your application able to
support a range of languages and locales. It involves Globalization and Localization.
Globalization : The processing of making an application
for a given language and regions (culture).
Localization : Making your application support a specific
language/localizable format.
Note : Some of the companies said Like
IBM and Microsystems, use the term “Globalization” for the combination of internationalization
and localization. As i described according Microsoft.
56) What is JSON Hijacking in ASP.NET
MVC3 and How will you use JSON Hijacking?
Ans:
Json stands for javascript object notation which
is used to interchange data between various languages a typical example is any
server side language like c#,vb.net with Javascript.
whenever you make an Ajax Call to retrieve some sort of data then the
best format to retrieve data is Json which is string:value pair.
IF any request has been blocked
means sensitive information could be
disclosed to third party web sites when this is used in a GET request. To allow
GET requests, set JsonRequestBehavior to AllowGet.
Its because Json only allow Json Post(as its more secure) Request but deny Get request because confidential information can not be retrieve using get request.
JSON
(pronounced like the English name, Jason) hijacking is a rare hack similar to
XSRF, except it’s targeted to request secure JSON from vulnerable applications.
The JSON hijacking process involves several steps:
1. A
conspiring site, via JavaScript, instructs the victim’s browser to request some
secure JSON data from another site.
2. The evil
JavaScript receives the JSON data.
3. If the
JSON is formatted as an array, the evil script can exploit browser JavaScript
processing code to read the JSON data and transmit it back to the attacking
site.
Solution For
JSON Hijacking :
Allow JSON via POST only The solution to this exploit offered by ASP.NET MVC 2 is to only accept requests for JSON data by HTTP POST requests, rather than by GETs. This is baked into and enforced by the standard JsonResult action result that ships with the framework. If we were to request data to be returned by JsonResult with a GET request, we wouldn’t receive the JSON data.
Implementing data in JSON response array by exposing sensitive data. when returning JSON response array. Add [AcceptVerbs(HttpVerbs.Post)] to make it http request return response type.(Cross Site Request Forgery (CSRF) attackk ) or XSRF.
I faced So
many Interviews and Real Time Experience in MVC3. I Hope These all interview
questions and answers Help full for mostly Experienced and Freshers.
Thanks
& Regards