Methods Explained) : Public Actionresult Someerror (Try Catch (Exception Ex) (Return View ("Error") ) )
Methods Explained) : Public Actionresult Someerror (Try Catch (Exception Ex) (Return View ("Error") ) )
Introduction
Further reading
But if we use this method then we will not be utilizing MVC exception mechanismproperly and
completely. In the further sections we will discuss five important ways by which we can utilize
MVC provided features for exception handling.
We have also set the exception so that it can be displayed inside the view.
}
}
To display the above error in view we can use the below code:-
@Model.Exception;
The problem with this approach is we cannot reuse the error handling logic across multiple
controllers.
Step 1 :- We need to first decorate the action method with “HandleError” attribute as shown in
the below code.
Step 2:- In the “Web.config” file you need to add the “customErrors” tag and point to the “Error”
view as shown in the below “Web.config” code snippet.
<system.web>
<customErrors defaultRedirect="Error.cshtml" mode="On">
</customErrors>
</system.web>
In case you want different error views for different exception types you can decorate action
method with multiple “HandleError” attribute point to multiple views as per exception types.
}
}
In order to reuse error handling logic across controller we can inherit from
“HandleErrorAttribute”class anddecorate this class as attribute across controller.
<system.web>
<customErrors
mode="On" defaultRedirect="Error1">
<error statusCode="404" redirect="~/Testing/NoPageFound"/>
</customErrors>
</system.web>
Any web application has two main execution steps first understanding the request and
depending on the type of the request sending out the appropriate response. MVC
application life cycle is not different it has two main phases first creating the request
object and second sending our response to the browser.
Creating the request object: -The request object creation has four major steps. Below is
the detail explanation.
Step 1 Fill route: MVC requests are mapped to route tables which in turn specify which
controller and action to be invoked. So if the request is the first request the first thing is
to fill the route table with routes collection. This filling of route table happens in the
global.asax file.
Step 2 Fetch route: Depending on the URL sent “UrlRoutingModule” searches the
route table to create “RouteData” object which has the details of which controller and
action to invoke.
Step 3 Request context created: The “RouteData” object is used to create the
“RequestContext” object.
Step 4 Controller instance created: This request object is sent to “MvcHandler”
instance to create the controller class instance. Once the controller class object is
created it calls the “Execute” method of the controller class.
Step 5 Creating Response object: This phase has two steps executing the action and
finally sending the response as a result to the view.
In the same time we can split many developers work at a time. It will not affects
one developer work to another developer work.
Latest version of MVC Support default responsive web site and mobile templates.
There are total nine return types we can use to return results from controller to view.
ViewResult (View): This return type is used to return a webpage from an action method.
PartialviewResult (Partialview): This return type is used to send a part of a view which
will be rendered in another view.
RedirectResult (Redirect): This return type is used to redirect to any other controller
and action method depending on the URL.
RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is used
when we want to redirect to any other action method.
ContentResult (Content): This return type is used to return HTTP content type like
text/plain as the result of the action.
jsonResult (json): This return type is used when we want to return a JSON message.
javascriptResult (javascript): This return type is used to return JavaScript code that will
run in browser.
FileResult (File): This return type is used to send binary output in response.
EmptyResult: This return type is used to return nothing (void) in the result.
MVC 6
ASP.NET MVC and Web API has been merged in to one.
Side by side - deploy the runtime and framework with your application
No need to recompile for every change. Just hit save and refresh the browser.
Dependency injection is inbuilt and part of MVC.
Everything packaged with NuGet, Including the .NET runtime itself.
New JSON based project structure.
Compilation done with the new Roslyn real-time compiler.
MVC 5
Asp.Net Identity
Attribute based routing
Bootstrap in the MVC template
Filter overrides
Authentication Filters
MVC 4
ASP.NET Web API
New mobile project template
Refreshed and modernized default project templates
Many new features to support mobile apps
MVC 3
Razor
HTML 5 enabled templates
JavaScript and Ajax
Support for Multiple View Engines
Model Validation Improvements
MVC 2
Templated Helpers
Client-Side Validation
Areas
Asynchronous Controllers
Html.ValidationSummary Helper Method
DefaultValueAttribute in Action-Method Parameters
Binding Binary Data with Model Binders
DataAnnotations Attributes
Model-Validator Providers
New RequireHttpsAttribute Action Filter
7. What are Filters in MVC?
Types of Filters:
Action Filters are additional attributes that can be applied to either a controller section or
the entire controller to modify the way in which action is executed. These attributes are
special .NET classes derived from System.Attribute which can be attached to classes,
methods, properties and fields.
Output Cache: This action filter caches the output of a controller action for a specified
amount of time.
Handle Error: This action filter handles errors raised when a controller action executes.
Authorize: This action filter enables you to restrict access to a particular user or role.
Output Cache
E.g.: Specifies the return value to be cached for 10 seconds.
publicclassActionFilterDemoController: Controller
{ [HttpGet]
OutputCache(Duration = 10)]
publicstringIndex()
{ returnDateTime.Now.ToString("T");
HTML helpers help you to render HTML controls in the view. For instance if you want to
display a HTML textbox on the view , below is the HTML helper code.
<%= Html.TextBox("FirstName") %>
For checkbox below is the HTML helper code. In this way we have HTML helper
methods for every HTML control that exists.
<%= Html.CheckBox("Yes") %>
There following HTML helpers can be used to render (modify and output) HTML form
elements:
BeginForm()
EndForm()
TextArea()
TextBox()
CheckBox()
RadioButton()
ListBox()
DropDownList()
Hidden()
Password()
Both provide the same HTML output, “HTML.TextBoxFor” is strongly typed while
“HTML.TextBox” isn’t. Below is a simple HTML code which just creates a simple
textbox with “FirstName” as name.
Html.TextBox("FirstName ")
Below is “Html.TextBoxFor” code which creates HTML textbox using the property name
‘FirstName” from object “m”.
Html.TextBoxFor(m => m.CustomerCode)
In the same way, we have for other HTML controls like for checkbox we have
“Html.CheckBox” and “Html.CheckBoxFor”.
A route is a URL pattern that is mapped to a handler. The handler can be a physical file,
such as a .aspx file in a Web Forms application. A handler can also be a class that
processes the request, such as a controller in an MVC application. To define a route,
you create an instance of the Route class by specifying the URL pattern, the handler,
and optionally a name for the route.
You add the route to the application by adding the Route object to the static Routes
property of the RouteTable class. The Routesproperty is a RouteCollection object that
stores all the routes for the application.
You typically do not have to write code to add routes in an MVC application. Visual
Studio project templates for MVC include preconfigured URL routes. These are defined
in the Mvc Application class, which is defined in the Global.asax file.
The route mapping code is written in "RouteConfig.cs" file and registered using
"global.asax" application start event.
13. What is the difference between Temp data, View, and View Bag?
ViewData
Requires typecasting for complex data type and checks for null values to avoid
error.
ViewBag
ViewBag is also used to pass data from the controller to the respective view.
ViewBag is a dynamic property that takes advantage of the new dynamic features
in C# 4.0
ViewBag.Name = "Yogesh";
Calling of ViewDatais :
ViewData["Name"] = "yogesh";
TempData
TempData is used to pass data from the current request to the next request
It keeps the information for the time of an HTTP Request. This means only from
one page to another. It helps to maintain the data when we move from one
controller to another controller or from one action to another action
It requires typecasting for complex data type and checks for null values to avoid
error. Generally, it is used to store only one time messages like the error
messages and validation messages
Example
For every page you would like to reuse the left menu, header, and footer controls. So
you can go and create partial views for each of these items and then you call that partial
view in the main view.
15. How did you create a partial view and consume it?
When you add a view to your project you need to check the “Create partial view” check
box.
Figure: Create partial view
Once the partial view is created you can then call the partial view in the main view using
the Html.RenderPartial method as shown in the below code snippet:
<body>
<div>
</div>
</body>
16. Explain what is the difference between View and Partial View?
View:
It contains the layout page.
Before any view is rendered, viewstart page is rendered.
View might have markup tags like body, html, head, title, meta etc.
View is not lightweight as compare to Partial View.
Partial View:
It does not contain the layout page.
Partial view does not verify for a viewstart.cshtml.We cannot put common code for a
partial view within the viewStart.cshtml.page.
Partial view is designed specially to render within the view and just because of that it
does not consist any mark up.
We can pass a regular view to the RenderPartial method.
In ASP.NET MVC 5.0 we have a new attribute route, By using the "Route" attribute we
can define the URL structure. For example in the below code we have decorated the
"GotoAbout" action with the route attribute. The route attribute says that the "GotoAbout"
can be invoked using the URL structure "Users/about".
[Route("Users/about")]
publicActionResultGotoAbout()
return View();
Razor is not a new programming language itself, but uses C# syntax for embedding
code in a page without the ASP.NET delimiters: <%= %>. It is a simple-syntax view
engine and was released as part of ASP.NET MVC 3. The Razor file extension is
"cshtml" for the C# language. It supports TDD (Test Driven Development) because it
does not depend on the System.Web.UI.Page class.
Authentication is giving access to the user for a specific service by verifying his/her identity
using his/her credentials like username and password or email and password. It assures that
the correct user is authenticated or logged in for a specific service and the right service has
been provided to the specific user based on their role that is nothing but authorization.
ASP.NET forms authentication occurs after IIS authentication is completed. You can
configure forms authentication by using forms element with in web.config file of your
application. The default attribute values for forms authentication are shown below:
<system.web>
<authenticationmode="Forms">
</authentication>
</system.web>
From ASP.Net MVC 2.0 Microsoft provided a new feature in MVC applications, Areas.
Areas are just a way to divide or “isolate” the modules of large applications in multiple or
separated MVC. like:
When you add an area to a project, a route for the area is defined in an AreaRegistration
file. The route sends requests to the area based on the request URL. To register routes
for areas, you add code to the Global.asax file that can automatically find the area
routes in the AreaRegistration file.
Create: It creates a View that helps in creating a new record for the Model. It
automatically generates a label and input field for each property in the Model.
Delete: It creates a list of records from the model collection along with the delete link
with delete record.
Details: It generates a view that displays the label and an input field of the each
property of the Model in the MVC framework.
Edit: It creates a View with a form that helps in editing the current Model. It also
generates a form with label and field for each property of the model.
List: It generally creates a View with the help of a HTML table that lists the Models from
the Model Collection. It also generates a HTML table column for each property of the
Model.
if (IsHtmlView)
else
This is very necessary for when we want to add a specific constraint to our URL. So, we
want to set some constraint string after our host name. Fine, let's see how to implement
it.
It's very simple to implement, just open the RouteConfig.cs file and you will find the
routing definition in that. And modify the routing entry as in the following. We will see that
we have added “abc” before.
Controller name, now when we browse we need to specify the string in the URL, as in
the following:
24. What is Output Caching in MVC?
The main purpose of using Output Caching is to dramatically improve the performance
of an ASP.NET MVC Application. It enables us to cache the content returned by any
controller method so that the same content does not need to be generated each time the
same controller method is invoked. Output Caching has huge advantages, such as it
reduces server round trips, reduces database server round trips, reduces network traffic
etc.
Caching In MVC
Caching In MVC
Caching In MVC
So our controller is ready, now we need to create simple view and after that, we will change our
Index action in the controller as below:
Hide Copy Code
So we are returning the current time from the controller. Isn’t it? Now refresh your view
frequently, let us say 2 times in 5 minutes, what is the output you are getting?
Caching In MVC
Caching In MVC
So have you noticed that within five minutes, we have hit the controller twice? Now here is the
magic of output cache. Please change your controller code as follows:
Now if you run and do the same exercise, you can notice that the controller will be hit only once
in a 5 minute duration. That’s cool right?
Even though it is so cool, there are some limitations too. As the memory becomes low, the cache
data will be released so that there won’t be cached data.
Here in our case, we just used a simple view which returns time from the controller. What if the
controller has some database operations, for every user’s hit, we need to go to the database
right? So in simple words, we can say that the caching is helping to reduce the amount of work
done that must be performed by our web server and database.
Now, we will see all the locations where we can save the cache data. Usually, the contents are
cached in three locations.
Web server
Proxy server
Web browser
You can always set where you want to save the cached data, whether it is in server, client or both
server and client by using location property. By default, the location will be ‘any’.
Caching In MVC
There are few situations that we should not cache in server. Let me explain, suppose we have a
controller which will return the country name of the user logged in to our application. Now I am
from ‘India’, so when I logged in to the application, it will show the country name as India. That’s
correct. Now have cached these data in the server. So what will happen if a user from Ireland
logged in to the application? Will it be good if we show India as his/her country? It does’t make
any sense, right?
So in short, we can say that we should not cache any personalized data in the server.
So what is the fix for this? Simple, cache the data in client. To do that, we can change our
controller as follows:
Have you noticed that we have set NoStore=true? This is to intimate the proxy server that
should not save any copies of these data in server.
The above mentioned implementation will make sure the different Employee Details view are
being generated for different users. Sound cool?
Cache Profiles
There is another way of achieving the caching, that is cache profiles, which is nothing but creating
a tag in web .config file and apply that for different controllers. In this way, you can have the same
cache profile for different controls. And also, it is easy to make any changes in the cache profile
since it is just a tag in the web.config file. Any changes in cache profile will get applied easily. I
found this is the most effective way of caching. We can do the cache profile as follows:
duration="86420" varyByParam="none"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
The above cache profile can be used for any admin control action which will be cached for one
day (60*60*24). You can simply use this profile as follows:
[OutputCache(CacheProfile="Admin")]
That is all about the caching. I will come with another post which explains caching in ASP.NET 5,
MVC 6 soon. Thanks for reading. Happy coding!
Once “TempData” is read in the current request it’s not available in the subsequent
request. If we want “TempData” to be read and also available in the subsequent request
then after reading we need to call “Keep” method as shown in the code below.
@TempData["MyData"];
TempData.Keep("MyData");
The more shortcut way of achieving the same is by using “Peek”. This function helps to
read as well advices MVC to maintain “TempData” for the subsequent request.
string str = TempData.Peek("MyData ").ToString();
Bundling and minification are two new techniques introduced to improve request load
time. It improves load time by reducing the number of requests to the server and
reducing the size of requested assets (such as CSS and JavaScript).
Bundling: It lets us combine multiple JavaScript (.js) files or multiple cascading style
sheet (.css) files so that they can be downloaded as a unit, rather than making individual
HTTP requests.
Minification: It squeezes out whitespace and performs other types of compression to
make the downloaded files as small as possible. At runtime, the process identifies the
user agent, for example IE, Mozilla, etc. and then removes whatever is specific to
Mozilla when the request comes from IE.
When you create a project a folder structure gets created by default under the name of
your project which can be seen in solution explorer. Below I will give you a brief
explanation of what these folders are for.
Model: This folder contains classes that is used to provide data. These classes can
contain data that is retrieved from the database or data inserted in the form by the user
to update the database.
Controllers: These are the classes which will perform the action invoked by the user.
These classes contains methods known as "Actions" which responds to the user action
accordingly.
Views: These are simple pages which uses the model class data to populate the HTML
controls and renders it to the client browser.
App_Start: Contains Classes such as FilterConfig, RoutesConfig, WebApiConfig. As of
now we need to understand the RouteConfig class. This class contains the default
format of the URL that should be supplied in the browser to navigate to a specified page.
Authorization filters
Action filters
Response filters
Exception filters
Razor View Engine introduced a new layout named _ViewStart which is applied on all
view automatically. Razor View Engine firstly executes the _ViewStart and then start
rendering the other view and merges them.
Example of Viewstart:
@ {
Layout = "~/Views/Shared/_v1.cshtml";
< title > ViewStart < /title> < /head> < body >
< /body> < /html>
Action methods on controllers return JsonResult (JavaScript Object Notation result) that
can be used in an AJAX application. This class is inherited from the "ActionResult"
abstract class. Here Json is provided one argument which must be serializable. The
JSON result object that serializes the specified object to JSON format.
public JsonResult JsonResultTest()
Calling of ViewData is :
ViewData["Name"] = " Vikash ";
@RenderBody()
</section>
</div>
GET
GET is used to request data from a specified resource. With all the GET request we
pass the URL which is compulsory, however it can take the following overloads.
.get(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ]
).done/.fail
POST
POST is used to submit data to be processed to a specified resource. With all the POST
requests we pass the URL which is compulsory and the data, however it can take the
following overloads.
.post(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
In the controller you can override the “OnException” event and set the “Result” to the
view name which you want to invoke when error occurs. In the below code you can see
we have set the “Result” to a view named as “Error”.
We have also set the exception so that it can be displayed inside the view.
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;
ViewName = "Error",
};
To display the above error in view we can use the below code
@Model.Exception;
Remote validation is the process where we validate specific data posting data to a
server without posting the entire form data to the server. Let's see an actual scenario, in
one of my projects I had a requirement to validate an email address, whether it already
exists in the database. Remote validation was useful for that; without posting all the data
we can validate only the email address supplied by the user.
Let's create a MVC project and name it accordingly, for me its
“TestingRemoteValidation”. Once the project is created let's create a model named
UserModel that will look like:
public class UserModel
[Required]
public string UserName
get;
set;
get;
set;
Let's get some understanding of the remote attribute used, so the very first parameter
“CheckExistingEmail” is the the name of the action. The second parameter “Home” is
referred to as controller so to validate the input for the UserEmailAddress the
“CheckExistingEmail” action of the “Home” controller is called and the third parameter is
the error message. Let's implement the “CheckExistingEmail” action result in our home
controller.
public ActionResult CheckExistingEmail(string UserEmailAddress)
{
try
Dependency Resolver again has been introduced in MVC3 and it is greatly simplified the
use of dependency injection in your applications. This turn to be easier and useful for
decoupling the application components and making them easier to test and more
configurable.
This is a general term that conveys a general philosophy, similar to the term REST
(Representational State Transfer). Unobtrusive JavaScript doesn't intermix JavaScript
code in your page markup.
Eg : Instead of using events like onclick and onsubmit, the unobtrusive JavaScript
attaches to elements by their ID or class based on the HTML5 data- attributes.