1. What is MVC?
Ans.
MVC is a framework used to
create web applications. The web application base builds on
Model-View-Controller pattern which separates the application logic from UI,
and the input and events from the user will be controlled by the Controller.
OR
MVC stands for Model-View-Controller. It is a software design pattern
which was introduced in 1970s. Also, MVC pattern forces a separation of concerns, it means domain model and controller logic
are decoupled from user interface (view). As a result maintenance and testing
of the application become simpler and easier.
2. Explain MVC design pattern?
Ans. MVC design pattern splits an application into three main aspects:
Model, View and Controller
Model - The Model represents a set of classes that describe
the business logic i.e. business model as well as data access operations i.e.
data model. It also defines business rules for data means how the data can be
changed and manipulated.
View - The View represents the UI components like CSS, jQuery,
html etc. It is only responsible for displaying the data that is received from
the controller as the result. This also transforms the model(s) into UI.
Controller - The Controller is responsible to process incoming
requests. It receives input from users via the View, then process the user's
data with the help of Model and passing the results back to the View.
Typically, it acts as the coordinator between the View and the Model.
3. How MVC pattern works in ASP.NET MVC?
Ans. Working of MVC pattern in ASP.NET MVC is explained as below:
The Model in ASP.NET MVC
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 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. This layer make use of Data Access Layer
for persisting data into database. Also, this layer is directly invoked by the
Controller to do processing on input data and sent back to view.
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 in ASP.NET MVC
The view is only responsible for displaying the data that is received
from the controller as a result. It also responsible for transforming a model
or models into UI which provide all the required business logic and validation
to the view.
By default, views are stored in the Views folder of an ASP.NET MVC
application.
The Controller in ASP.NET MVC
The Controller in ASP.NET MVC, respond to HTTP requests and determine
the action to take based upon the content of the incoming request. It receives
input from users via the View, then process the user's data with the help of
Model and passing the results back to the View.
By default, controllers are stored in the Controllers folder an ASP.NET
MVC application.
4.
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:
1. User interacts with the Controller.
2. There is one-to-many relationship between Controller
and View means one controller can mapped to multiple views.
3. Controller and View can have a reference to model.
4. Controller and View can talk to each other.
5. Model and View cannot talk to each other directly. They communicate
to each other with the help of controller.
5. What are advantages of ASP.NET MVC?
Ans. There are following advantages of ASP.NET MVC over Web Forms (ASP.NET):
•
Separation of concern - MVC design pattern divides the ASP.NET MVC application
into three main 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 then Web
Forms.
•
Full control over application behavior - MVC framework doesn’t use View State or server based
forms like Web Forms. This gives the application developer more control over
the behaviors of the application and also reduces the bandwidth of requests to
the server.
•
ASP.NET features are supported - MVC framework is built on top of ASP.NET and therefore
can use most of the features that ASP.NET include such as the providers
architecture, authentication and authorization scenarios, membership and roles,
caching, session and more.
•
URL routing mechanism - MVC framework supports a powerful URL routing
mechanism that helps to build a more comprehensible and searchable URLs in your
application. This mechanism helps to the application to be more addressable
from the eyes of search engines and clients and can help in search engine
optimization.
6. What is difference between 3-layer
architecture and MVC architecture?
Ans. 3-layer architecture separates the application into 3 components which
consists of Presentation Layer Business Layer and Data Access Layer. In 3-layer
architecture, user interacts with the Presentation layer. 3-layer is a linear
architecture.
MVC architecture separates the application into three components which
consists of Model, View and Controller. In MVC architecture, user interacts
with the controller with the help of view. MVC is a triangle architecture.
MVC does not replace 3-layer architecture. Typically 3-layer and MVC
are used together and MVC acts as the Presentation layer.
7. Explain ASP.NET MVC Pipeline/Page
Life Cycle?
Ans. The detail ASP.NET MVC pipeline is given below:
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.
The UrlRoutingModule(System.Web.Routing.UrlRoutingModule) is a class
which matches an incoming HTTP request to a registered route pattern in the
RouteTable(System.Web.Routing.RouteTable).
2. Controller Initialization - The MvcHandler initiates the real processing inside
ASP.NET MVC pipeline by using ProcessRequest method. This method uses the
IControllerFactory instance (default is
System.Web.Mvc.DefaultControllerFactory) to create corresponding controller.
3. Action
Execution – Action execution occurs
in the following steps:
•
When the
controller is initialized, the controller calls its own InvokeAction() method
by passing the details of the chosen action method. This is handled by the
IActionInvoker.
•
After chosen of
appropriate action method, model binders(default is
System.Web.Mvc.DefaultModelBinder) retrieves the data from incoming HTTP
request and do the data type conversion, data validation such as required or
date format etc. and also take care of input values mapping to that action
method parameters.
•
Authentication
Filter was introduced with ASP.NET MVC5 that run prior to authorization filter.
It is used to authenticate a user. Authentication filter process user
credentials in the request and provide a corresponding principal. Prior to
ASP.NET MVC5, you use authorization filter for authentication and authorization
to a user.
•
By default,
Authenticate attribute is used to perform Authentication. You can easily create
your own custom authentication filter by implementing IAuthenticationFilter.
•
Authorization
filter allow you to perform authorization process for an authenticated user.
For example, Role based authorization for users to access resources.
•
By default,
Authorize attribute is used to perform authorization. You can also make your
own custom authorization filter by implementing IAuthorizationFilter.
•
Action filters
are executed before (OnActionExecuting) and after (OnActionExecuted) an action
is executed. IActionFilter interface provides you two methods OnActionExecuting
and OnActionExecuted methods which will be executed before and after an action
gets executed respectively. You can also make your own custom ActionFilters
filter by implementing IActionFilter. For more about filters refer this article
Understanding ASP.NET MVC Filters and Attributes
•
When action is
executed, it process the user inputs with the help of model (Business Model or
Data Model) and prepare Action Result.
4. Result
Execution - Result execution occurs
in the following steps:
•
Result filters
are executed before (OnResultExecuting) and after (OnResultExecuted) the
ActionResult is executed. IResultFilter interface provides you two methods
OnResultExecuting and OnResultExecuted methods which will be executed before
and after an ActionResult gets executed respectively. You can also make your
own custom ResultFilters filter by implementing IResultFilter.
•
Action Result is
prepared by performing operations on user inputs with the help of BAL or DAL.
The Action Result type can be ViewResult, PartialViewResult,
RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult
and EmptyResult.
•
Various Result
type provided by the ASP.NET MVC can be categorized into two category-
ViewResult type and NonViewResult type. The Result type which renders and
returns an HTML page to the browser, falls into ViewResult category and other
result type which returns only data either in text format, binary format or a
JSON format, falls into NonViewResult category.
4.1 View Initialization and Rendering - View Initialization and Rendering execution occurs in
the following steps:
•
ViewResult type
i.e. view and partial view are represented by IView (System.Web.Mvc.IView)
interface and rendered by the appropriate View Engine.
•
This process is
handled by IViewEngine (System.Web.Mvc.IViewEngine) interface of the view
engine. By default ASP.NET MVC provides WebForm and Razor view engines. You can
also create your custom engine by using IViewEngine interface and can
registered your custom view engine in to your ASP.NET MVC application as shown below:
•
Html Helpers are
used to write input fields, create links based on the routes, AJAX-enabled
forms, links and much more. Html Helpers are extension methods of the
HtmlHelper class and can be further extended very easily. In more complex
scenario, it might render a form with client side validation with the help of
JavaScript or jQuery.
8. Difference between ViewData, ViewBag, TempData, Session. Session
Management in MVC
Ans : ViewData
• ViewData is a dictionary object that is derived from ViewDataDictionary class.
• publicViewDataDictionaryViewData { get; set; }
• ViewData is a property of ControllerBase class.
• ViewData is used to pass data from controller to corresponding view.
• Its life lies only during the current request.
• If redirection occurs then its value becomes null.
• It’s required typecasting for getting data and check for null values to avoid error.
Syntex:
Controller
Code to assign data to ViewData.
ViewData["_firstName"]
= _model.NameFirst;
Access
ViewData value on View.
@Html.TextBox("FirstName",
ViewData["FirstName"]
ViewBag
•
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0., Whereas ViewBag not present in MVC 1.0,2.0,3.0.
• Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
• publicObjectViewBag { get; }
• ViewBag is a property of ControllerBase class.
• Its life also lies only during the current request.
• If redirection occurs then its value becomes null.
• It doesn’t required typecasting for getting data.
Syntex:
Controller
Code to assign data to ViewBag.
ViewBag.Message
= "My message";
Access
ViewBag value on View.
@Html.TextBox("Message",ViewBag.Message)
TempData
• TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.• publicTempDataDictionaryTempData { get; set; }• TempData is a property of ControllerBase class.• 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 is used to store only one time messages like error messages, validation messages. To persist data with TempData.
Session
• Session is an object that is derived from HttpSessionState class.• publicHttpSessionStateSession { get; }• Session is a property of HttpContext class.• Session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it never expires.• 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.
9.
What is 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
Forms
|
ASP.NET MVC
|
1. ASP.NET Web Form follows a traditional event
driven development model.
|
1. ASP.NET MVC is a lightweight and follow MVC
(Model, View, and Controller) pattern based development model.
|
2. ASP.NET Web Form has server controls.
|
2. ASP.NET MVC has html helpers.
|
3. ASP.NET Web Form has state
management (like as view state, session) techniques.
|
3. ASP.NET MVC has no automatic state management
techniques.
|
4. ASP.NET Web Form has
file-based URLs means file name exist in the URLs must have its physically
existence.
|
4. 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.
|
5. ASP.NET Web Form follows WebForm Syntax
|
5. ASP.NET MVC follow customizable syntax (Razor
as default)
|
6. In ASP.NET Web Form, Web Forms (ASPX) i.e.
views are tightly coupled to Code behind (ASPX.CS) i.e. logic.
|
6. In ASP.NET MVC, Views and logic are kept separately.
|
7. ASP.NET Web Form has Master Pages for
consistent look and feels.
|
7. ASP.NET MVC has Layouts for consistent look and
feels.
|
8. ASP.NET Web Form has User Controls for code
re-usability.
|
8. ASP.NET MVC has Partial Views for code
re-usability.
|
9. ASP.NET Web Form has built-in data controls and
best for rapid development with powerful data access.
|
9. ASP.NET MVC is lightweight, provide full
control over mark-up and support many features that allow fast & agile
development. Hence it is best for developing interactive web application with
latest web standards.
|
10. ASP.NET Web Form is not Open Source.
|
10. ASP.NET Web MVC is an Open Source.
|
10. What is ViewModel in ASP.NET MVC?
Ans. In ASP.NET MVC, ViewModel is a class that contains the fields which are
represented in the strongly-typed view. It is used to pass data from controller
to strongly-typed view.
Key Points about ViewModel
•
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.
11. What is Routing in ASP.NET MVC?
Ans. Routing is a pattern matching system that monitor the incoming request
and figure out what to do with that request. At runtime, Routing engine use the
Route table for matching the incoming request's URL pattern against the URL
patterns defined in the Route table. You can register one or more URL patterns
to the Route table at Application_Start event.
12. How to define a route in ASP.NET
MVC?
Ans. You can define a route in ASP.NET MVC as given below:
// default Route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
Ans. Many developers compare routing to URL rewriting since both look
similar and can be used to make SEO friendly URLs. But both the approaches are
very much different. The main difference between routing and url rewriting is
given below:
•
URL rewriting is
focused on mapping one URL (new url) to another URL (old url) while routing is
focused on mapping a URL to a resource.
•
URL rewriting
rewrites your old url to new one while routing never rewrite your old url to
new one but it map to the original route.
14. What are important namespaces in
ASP.NET MVC?
Ans. There are some important namespaces as given below:
•
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 supports Ajax scripting in an
ASP.NET MVC application. The namespace includes support for Ajax scripts and
Ajax option settings as well.
•
System.Web.Mvc.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.
15. What are Layouts in ASP.NET MVC?
Ans. Layouts are used to maintain a consistent look and feel across multiple views within ASP.NET MVC application. As compared to Web Forms, layouts serve the same purpose as master pages, but offer a simple syntax and greater flexibility.
16. What are Sections in ASP.NET MVC?
16. What are Sections in ASP.NET MVC?
Ans. A section allow you to specify a
region of content within a layout. It expects one parameter which is the name
of the section. If you don’t provide that, an exception will be thrown. A
section in a layout page can be defined by using the following code.
@section Footer { <p>Section/Index page</p> }
You can render above defined section header on
the content page as given below:
@RenderSection("footer", required: false)
By default, sections are mandatory. To make sections
optional, just provides the second parameter value as false, which is a
Boolean value.
@RenderSection("footer", false)
|
Note: A view can define only those sections that are referred to in the
layout page otherwise an exception will be thrown
17. 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>
RenderPage method also exists in the Layout page to render other page
exists in your application. A layout page can have multiple RenderPage method.
@RenderPage("~/Views/Shared/_Header.cshtml")
18. What are different ways of
returning/rendering a view in ASP.NET MVC?
Ans. There are four different ways for returning/rendering a view in
ASP.NET MVC as given below:
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, 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 construct a redirect url to a specific
action/controller in your application and use the route table to generate the
correct URL. RedirectToAction cause 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, 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().
19. What are Action methods in ASP.NET
MVC?
Ans. Controller actions are methods defined in the controller class and
responsible to perform required operations on the user's inputs like as form
values, query strings values etc. with the help of Model and passing the
results back to the View. Asp.net MVC has the following built-in ActionResults
Type and Helper methods:
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.
5. ContentResult - Returns a ContentResult which renders raw text like as
"Hello, DotNet Tricks!" by using controller Content() helper method.
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.
20. What is Data Annotations in ASP.NET
MVC?
Ans. Data validation is a key aspect for developing web application. In
Asp.net MVC, we can easily apply validation to web application by using Data
Annotation attribute classes to 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.
Data Annotation Validator Attributes
•
DataType -
Specify the datatype of a property
•
DisplayName -
specify the display name for a property.
•
DisplayFormat -
specify the display format for a property like different format for Date
property.
•
Required -
Specify a property as required.
•
ReqularExpression - validate the value of a property by specified regular expression
pattern.
•
Range -
validate the value of a property within a specified range of values.
•
StringLength -
specify min and max length for a string property.
•
MaxLength -
specify max length for a string property.
•
Bind -
specify fields to include or exclude when adding parameter or form values to
model properties.
•
ScaffoldColumn -
specify fields for hiding from editor forms.
21. How to apply Server side validation
in ASP.NET MVC?
Ans. Server side validations are very important before playing with
sensitive information of a user. Server-side validation must be done whether we
validate the received data on the client side. User could disable script in his
browser or do something else to bypass client-side validation. In this case
server-side validation must require to protect our data from dirty input.
In ASP.NET MVC, there are two ways to validate a model on server side:
Explicit Model Validation – This is the traditional way to validate the model data
by using IF..Else..IF statement. In this way, you need to check your model
property values one by one for your desired result. If model property values
are unexpected, inject error messages within ModelState.
if (ModelState.IsValid)
{
//Model is valid. Call Service layer for further processing of data
} else {
//Validation failed. Return the model to the user with the relevant error messages
}
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.
[Required]
[StringLength(60, MinimumLength = 4)]
[Display(Name = "First Name")]
public string FirstName
{
get;
set;
}
22. How to enable and disable
client-side validation in ASP.NET MVC?
Ans. We can enable and disable the
client-side validation by setting the values of ClientValidationEnabled &
UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied
to application level.
<add key="ClientValidationEnabled"
value="true" />
<add
key="UnobtrusiveJavaScriptEnabled" value="true" />
|
For client-side validation, the values of above both the keys must be
true. When we create 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 with in the Application_Start()
event of the Global.asax, as shown below. protected void Application_Start()
{
//Enable or Disable Client Side Validation at
Application Level
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}
|
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 overrides the application
level settings for that specific view.
@using MvcApp.Models
@{
ViewBag.Title = "About";
HtmlHelper.ClientValidationEnabled = false;
}
23. What is Bundling and Minification in
ASP.NET MVC?
Ans. ASP.NET MVC4 and .NET Framework 4.5 offer bundling and minification
techniques that reduce the number of request to the server and size of
requested CSS and JavaScript, which improve page loading time.
A bundle is a logical group of files that
is 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 create with
in BundleConfig.cs file. public class BundleConfig
{
public static void
RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
"~/Content/mystyle.min.css"));
bundles.Add(new
ScriptBundle("~/bundles/jqueryval").Include(
|
www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 51
"~/Scripts/jquery-1.7.1.min.js",
"~/Scripts/jquery.validate.min.js",
"~/Scripts/jquery.validate.unobtrusive.min.js"));
}
}
|
Minification is 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 two most
popular tools for minifying js and css files.
CSS and JS files Without Bundling and
Minification
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.
<link href="~/Content/Site.css"
rel="stylesheet"/>
<link href="~/Content/MyStyle.css"
rel="stylesheet"/>
<script
src="~/Scripts/jquery-1.7.1.js"></script>
<script
src="~/Scripts/jquery-ui-1.8.20.js"></script>
<script
src="~/Scripts/jquery.validate.js"></script>
<script
src="~/Scripts/jquery.validate.unobtrusive.js"></script>
|
24. What is Partial View in ASP.NET MVC?
Ans. A partial view is like as user control in ASP.NET Web forms that is
used for code re-usability. Partial views helps us to reduce code duplication.
Hence partial views are reusable views like as Header and Footer views.
We can use partial view to display blog comments, product category,
social bookmarks buttons, a dynamic ticker, calendar etc.
It is best practice to create 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.
25. How do you return a partial view
from controller?
Ans. return PartialView(options);
Where options could be a Model or a View name
26. 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 used 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, we would like to use RenderPartial method since an article information
with comments are 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 from 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 category is populated by the different model.
|
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
•
Renders the
partial view as an HTML-encoded string.
•
This method
result can be stored in a variable, since it returns string type value.
•
Simple to use and
no need to create any action.
Partial method is useful used 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, we would like to use RenderPartial method since an
article information with comments are already populated in the view model.
@Html.Partial("_Comments")
|
Html.Action
•
Renders the
partial view as an HtmlString .
•
For this method,
we need to create a child action for the rendering the partial view.
•
This method
result can be stored in a variable, since it returns string type value.
•
Action method is
useful when the displaying data in the partial view is independent from
corresponding view model. For example: In a blog to show category list on each
and every page, we would like to use Action method since the list of category
is populated by the different model.
@{Html.Action("Category","Home");}
|
27. What is caching and when to use it?
Ans. Caching is a most important aspect of 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.
When to use caching
•
Use caching for
contents that are accessed frequently.
•
Avoid caching for
contents that are unique per user.
•
Avoid caching for
contents that are accessed infrequently/rarely.
•
Use the
VaryByCustom function to cache multiple versions of a page based on
customization aspects of the request such as cookies, role, theme, browser, and
so on.
•
For efficient
caching use 64-bit version of Windows Server and SQL Server.
•
For database
caching make sure your database server has sufficient RAM otherwise, it may
degrade the performance.
•
For caching of
dynamic contents that change frequently, define a short cache–expiration time
rather than disabling caching.
28. What are advantages of caching?
Ans. There are following advantages of caching:
•
Reduce hosting
server round-trips
•
When content is
cached at the client or in proxies, it cause minimum request to server.
•
Reduce database
server round-trips
•
When content is
cached at the web server, it can eliminate the database request.
•
Reduce network
traffic
•
When content is
cached at the client side, it also reduce the network traffic.
•
Avoid
time-consumption for regenerating reusable content
•
When reusable
content is cached, it avoid the time consumption for regenerating reusable
content.
•
Improve
performance
•
Since cached
content reduce round-trips, network traffic and
29. What are the different Session state
management options available in ASP.NET?
Ans : 1. In-Process
2. Out-of-Process.
In-Process stores the session in memory on the web server.
Out-of-Process Session state management stores data in an external
server. The external server may be either a SQL Server or a State Server. All
objects stored in session are required to be serializable for Out-of-Process
state management.
30. What is boxing and unboxing?
Ans.
Boxing is assigning a value
type to reference type variable.
Unboxing is reverse of boxing i.e. Assigning reference
type variable to value type variable.
31. Strongly typed view?
Ans: The view which bind with any model is
called as strongly typed view. You can bind any class as model to view. You can
access model properties on that view. You can use data associated with model to
render controls.
You can bind custom types as well as primitive types like string, array, list etc. to view. e.g.
public class UserModel {}
Controller -
public ActionResult View1()
{
UserModel obj = new UserModel();
return view(obj)
}
View -
@model MyProject.UserModel
OR
Controller -
public ActionResult View1()
{
string[] arrStr = new string[5];
return view(arrStr)
}
View -
@model string[]
Again Main advantage of using strongly typed view is - You can same object during posting view. So Whater values assigned to controls associated models property. You can access in post action-
[HTTPPOST]
public ActionResult View1(UserModel obj)
{
obj.save();
return view();
}
It will be very using to post model at server side. Suppose we using strongly typed to add something. We can model details in post action and we can perform save operation on that object.
You can bind custom types as well as primitive types like string, array, list etc. to view. e.g.
public class UserModel {}
Controller -
public ActionResult View1()
{
UserModel obj = new UserModel();
return view(obj)
}
View -
@model MyProject.UserModel
OR
Controller -
public ActionResult View1()
{
string[] arrStr = new string[5];
return view(arrStr)
}
View -
@model string[]
Again Main advantage of using strongly typed view is - You can same object during posting view. So Whater values assigned to controls associated models property. You can access in post action-
[HTTPPOST]
public ActionResult View1(UserModel obj)
{
obj.save();
return view();
}
It will be very using to post model at server side. Suppose we using strongly typed to add something. We can model details in post action and we can perform save operation on that object.
33. Attribute Routing
Ans: Routing
in MVC and Web API is a pattern matching system that matches incoming request
and figure out what to do with that request. Inside application Routing engine
uses defined Route table for matching URI to an action. We have opportunity to
define one or more routes in the route table. We register this route table in
Application_Start (Global.asax) using following code.
Routing is a pattern matching process that monitors the requests and determines what to do with each request. In other words we can say Routing is a mechanism for mapping requests within our MVC application.
When a MVC application starts the first time, the Application_Start () event of global.asax is called. This event registers all routes in the route table using the RouteCollection.MapRoute method.
publicclass HomeController : Controller
{
[Route("Users/about")]
public ActionResult About()
{
ViewBag.Message = "You successfully reached USERS/About route";
return View();
}
}
[RoutePrefix("Movie")]
publicclass HomeController : Controller
{
//Route: Movie/Index
public ActionResult Index()
{
ViewBag.Message = "You are in Home Index";
return View();
}
//Route: Movie/About
public ActionResult About()
{
ViewBag.Message = "You successfully reached USERS/About route";
return View();
}
}
34. Difference between MVC2 Vs MVC3
Vs MVC4 Vs MVC5 Vs MVC6
Ans:
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
35. What is Dependency Injection?
Ans: In software engineering, dependency injection is a software design pattern that
implements inversion of control for resolving dependencies. Dependency injection means giving an object its instance
variables. Really. That's it.
The advantages of using the
Dependency Injection pattern and Inversion of Control are the following:
· Reduces class coupling· Increases code reuse· Improves code maintainability· Improves application testing
36. Understanding MVC, MVP and MVVM Design Patterns?
Ans: There are three most popular
MV-* design patterns: MVC, MVP and MVVM. These are widely used by the various
technologies. In this article, I will provide my opinion on these three.
MVC
Pattern
MVC stands for Model-View-Controller. It is a software
design pattern which was introduced in 1970s. Also, MVC pattern forces a
separation of concerns, it means domain model and controller logic are
decoupled from user interface (view). As a result maintenance and testing of
the application become simpler and easier.
MVC design pattern splits an application into three main
aspects: Model, View and Controller
1.
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.
2.
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.
3.
Controller
The Controller is responsible to process incoming requests. It receives
input from users via the View, then process the user's data with the help of
Model and passing the results back to the View. Typically, it acts as the
coordinator between the View and the Model.
Today, this pattern is used by many popular framework like
as Ruby on Rails, Spring Framework, Apple iOS Development and ASP.NET MVC.
MVP
pattern
This pattern is similar to MVC pattern in which controller
has been replaced by the presenter. This design pattern splits an application
into three main aspects: Model, View and Presenter.
1.
Model
The Model represents a set of classes that describes the business logic
and data. It also defines business rules for data means how the data can be
changed and manipulated.
2.
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.
3.
Presenter
The Presenter is responsible for handling all UI events on behalf of the
view. This receive input from users via the View, then process the user's data
with the help of Model and passing the results back to the View. Unlike view
and controller, view and presenter are completely decoupled from each other’s
and communicate to each other’s by an interface.
Also, presenter does not manage the incoming request traffic as
controller.
This pattern is commonly used with ASP.NET Web Forms
applications which require to create automated unit tests for their code-behind
pages. This is also used with windows forms.
Key
Points about MVP Pattern:
1.
User interacts with the View.
2.
There is one-to-one relationship between View and
Presenter means one View is mapped to only one Presenter.
3.
View has a reference to Presenter but View has not reference
to Model.
4.
Provides two way communication between View and
Presenter.
MVVM
pattern
MVVM stands for Model-View-View Model. This pattern
supports two-way data binding between view and View model. This enables
automatic propagation of changes, within the state of view model to the View.
Typically, the view model uses the observer pattern to notify changes in the
view model to model.
1.
Model
The Model represents a set of classes that describes the business logic
and data. It also defines business rules for data means how the data can be
changed and manipulated.
2.
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.
3.
View Model
The View Model is responsible for exposing methods, commands, and other
properties that helps to maintain the state of the view, manipulate the model
as the result of actions on the view, and trigger events in the view itself.
This pattern is commonly used by the WPF, Silverlight,
Caliburn, nRoute etc.
Key
Points about MVVM Pattern:
1.
User interacts with the View.
2.
There is many-to-one relationship between View and
ViewModel means many View can be mapped to one ViewModel.
3.
View has a reference to ViewModel but View Model has no
information about the View.
4.
Supports two-way data binding between View and
ViewModel.
What do you think?
I hope you have understand the MVC, MVP and MVVM design
patterns. I would like to have feedback from my blog readers. Your valuable
feedback, question, or comments about this article are always welcome.
37. What is Area in MVC?
Ans : Areas are an ASP.NET
MVC feature used to organize related functionality into a group as a separate
namespace (for routing) and folder structure (for views). Using areas creates a
hierarchy for the purpose of routing by adding another route parameter, area,
to controller and action.
Areas provide a way to
partition a large ASP.NET Core MVC Web app into smaller functional groupings.
An area is effectively an MVC structure inside an application. In an MVC
project, logical components like Model, Controller, and View are kept in
different folders, and MVC uses naming conventions to create the relationship
between these components. For a large app, it may be advantageous to partition
the app into separate high level areas of functionality. For instance, an
e-commerce app with multiple business units, such as checkout, billing, and
search etc. Each of these units have their own logical component views,
controllers, and models. In this scenario, you can use Areas to physically
partition the business components in the same project.
An area can be defined as
smaller functional units in an ASP.NET Core MVC project with its own set of
controllers, views, and models.
38. Authentication Filters?
Ans: So what is the real reason behind Authentication
filters?
Prior to authentication filters,
developers used the Authorization filters to drive some of the authentication
tasks for the current request. It was convenient because the Authorization
filters were executed prior to any other action filters. For example,
before the request routes to action execution, we would use an Authorization
filter to redirect an unauthenticated user to a login page. Another example
would be to use the Authorization filter to set a new authentication principal,
which is different from the application’s original principal in context.
Authentication related tasks can now be
separated out to a new custom authentication filter and authorization related
tasks can be performed using authorization filters. So it is basically about
separating of concerns, while giving developers more flexibility to drive
authentication using ASP.NET MVC infrastructure.
39. How to
access globally TempData value in MVC?
TempData value in MVC?
TempData keep() vs peek()
When an object in
a
TempDataDictionary
is read, it will be
marked for deletion at the end of that request.
That means if you put something on TempData like
TempData["value"] = "someValueForNextRequest";
And on another request you access it, the value will be
there but as soon as you read it, the value will be marked for deletion:
//second request, read value and is marked for deletion
object value = TempData["value"];
//third request, value is not there as it was deleted at the end of the second request
TempData["value"] == null
The
Peek
and Keep
methods
allow you to read the value without marking it for deletion. Say we get back to
the first request where the value was saved to TempData.
With
Peek
you
get the value without marking it for deletion with a single call.//second request, PEEK value so it is not deleted at the end of the request
object value = TempData.Peek("value");
//third request, read value and mark it for deletion
object value = TempData["value"];
With
Keep
you
specify a key that was marked for deletion that you want to keep. Retrieving
the object and later on saving it from deletion are 2 different calls.//second request, get value marking it from deletion
object value = TempData["value"];
//later on decide to keep it
TempData.Keep("value");
//third request, read value and mark it for deletion
object value = TempData["value"];
You can use
Peek
when
you always want to retain the value for another request.
Use
Keep
when
retaining the value depends on additional logic.
TempData is also a dictionary object that stays for the
time of an HTTP Request. So, TempData can be used to maintain data between one
controller action to the other controller action.
TempData is used to check the null values each time.
TempData contain two method keep() and peek() for maintain data state from one
controller action to others.
When TempDataDictionary object
is read, At the end of request marks as deletion to current read object.
The keep() and peek() method
is used to read the data without deletion the current read object.
You
can use Peek() when you always want to hold/prevent the value
for another request. You can useKeep() when prevent/hold the value
depends on additional logic.
Overloading
in TempData.Peek() & TempData.Keep() as given below.
TempData.Keep() have 2 overloaded methods.
1. void keep() : That menace all the data not deleted on
current request completion.
2. void keep(string key) : persist the specific item in TempData with
help of name.
TempData.Peek() no overloaded methods.
1. object peek(string key) : return an object that contain items with
specific key without making key for deletion.
2.
1.
40. Types of constructor in MVC?
Types of Constructors
Basically constructors are 5
types those are
1.
Default Constructor
2.
Parameterized Constructor
3.
Copy Constructor
4.
Static Constructor
5.
Private Constructor
41. What is Scaffolding in ASP.NET MVC?
Ans:
Scaffolding is a technique used by many MVC frameworks like ASP.NET MVC, Ruby
on Rails, Cake PHP and Node.JS etc., to generate code for basic CRUD (create,
read, update, and delete) operations against your database effectively. Further
you can edit or customize this auto generated code according to your need.
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 Website.
How Scaffold templates works in ASP.NET MVC.
Scaffold templates are used to generate code for basic
CRUD operations within your ASP.NET MVC applications against your database with
the help Entity Framework. These templates use the Visual Studio T4 templating
system to generate views for basic CRUD operations with the help of Entity
Framework.
Run time vs Design time Scaffolding Entity Framework.
Scaffolding can occur at two different phases of the
program lifecycle: design time and run time. Design time scaffolding produces
files of code that can later be modified by the programmer to customize the way
the application database is used. However, for large-scale applications this
approach may be difficult to maintain due to the sheer number of files
produced, and the fact that the design of the files was largely fixed when they
were generated or copied from the original templates.
Alternatively, run time scaffolding produces code on
the fly. It allows changes to the design of the templates to be immediately
reflected throughout the application. But modifying the design of the templates
may be more difficult or impractical in the case of run time scaffolding.
42. Types of filters in MVC?
ASP.NET
MVC Filters are used to inject extra logic at the different levels of MVC
Framework request processing. Filters provide a way for cross cutting concern
(logging, authorization, and caching).
Filter Type
|
Interface
|
Description
|
Authentication
|
IAuthenticationFilter
|
These are Runs, before any other filters or the action
method.
|
Authorization
|
IAuthorizationFilter
|
These Runs first, before any other filters or the
action method.
|
Action
|
IActionFilter
|
These Runs before and after the action method.
|
Result
|
IResultFilter
|
Runs before and after the action result is executed.
|
Exception
|
IExceptionFilter
|
Runs only if another filter, the action method, or the
action result throws an exception.
|
43. What is AllowAnonymous attribute in mvc [Resolved]
For ex:
I have three pages named
LOGIN, HOME, DETAILS.
Suppose that, we can access
home, Details pages if we are authorized only.
To provide authorization we
are using a login page.
Now, I want to provide
authorization using [Authorize] filter defined in Filter.config file.
Then Authorization is
applied to all pages (login also). Hence we cannot access login page also.
To allow login page access
initially, we have to provide [AllowAnonymous] to login page.
Now, login page will open
initially, after authorization, we can access remaining two pages
[AllowAnonymous] - Anyone can access view related to the action
in controller
[Authorize] - Only registered users or specific set of users can
access view related to the action in controller
You can also specify list of
users in the attribute to grant access to them
44. What is
html helpers in MVC?
Ans: Use of HTML helpers in a view to render HTML content. An HTML helper,
in most cases, is just a method that returns a string.
You can build an entire ASP.NET MVC application without using a
single HTML helper. However, HTML helpers make your life as a developer easier.
By taking advantage of helpers, you can build your views with far less work.
45.
What is Ajax Helpers in Asp.Net
MVC?
Ans: In
today modern era people want rich web applications for developing this kind
application we need to use AJAX in one or other way. By using ajax helpers in
asp.net mvc we can send data to server in asynchronous way without post
backs that will make our applications interactive, easy to use and will make
end user happy.
By using
AJAX we can update partial part of view without posting entire page to
server. Here we are going to see how to use AJAX helper in asp.net mvc to
submit forms and using AJAX action link to invoke action method asynchronously
by using JavaScript. Before starting with demo on AJAX helper let's have
look on various properties of Ajax Options.
Di 46. Difference between ApiController and Controller in ASP.NET MVC?
3. Ans: Note If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.
4. Use Controller to render your normal views. ApiController action only return data that is serialized and sent to the client.
5. ApiControllers are specialized in returning data. For example, they take care of transparently serializing the data into the format requested by the client. Also, they follow a different routing scheme by default (as in: mapping URLs to actions), providing a REST-ful API by convention.
6. You could probably do anything using a Controller instead of an ApiController with the some (?) manual coding. In the end, both controllers build upon the ASP.NET foundation. But having a REST-full API is such a common requirement today that WebAPI was created to simplify the implementation of a such an API.
7. It's fairly simple to decide between the two: if you're writing an HTML based web/internet/intranet application - maybe with the occasional AJAX call returning json here and there - stick with MVC/Controller. If you want to provide a data driven/REST-ful interface to a system, go with WebAPI. You can combine both, of course, having an ApiController cater AJAX calls from an MVC page.
No comments:
Post a Comment