Most Asked ASP - Net MVC Interview Questions and Answers C Sharp Corner
Most Asked ASP - Net MVC Interview Questions and Answers C Sharp Corner
Answer:
Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given
software application into three interconnected parts, so as to separate internal representation of information from the
way that information is presented to or accepted from the user.
MVC is a framework for building web applications using a MVC (Model View Controller) design:
The Model represents the application core (for instance a list of database records).
The View displays the data (the database records).
The Controller handles the input (to the database records).
The MVC model also provides full control over HTML, CSS, and JavaScript.
The Model is the part of the application that handles the logic for the application data.
Often model objects retrieve data (and store data) from a database.
The View is the part of the application that handles the display of the data.
Most often the views are created from the model data.
The Controller is the part of the application that handles user interaction.
Typically controllers read data from a view, control user input, and send input data to the model.
The MVC separation helps you manage complex applications, because you can focus on one aspect a time. For
example, you can focus on the view without depending on the business logic. It also makes it easier to test an
application.
The MVC separation also simplifies group development. Different developers can work on the view, the controller
logic, and the business logic in parallel.
Change Accommodation
User interfaces tend to change more frequently than business rules (different colors, fonts, screen layouts,
and levels of support for new devices such as cell phones or PDAs) because the model does not depend on
the views, adding new types of views to the system generally does not affect the model. As a result, the
scope of change is confined to the view.
Separation of Concerns is one of the core advantages of ASP.NET MVC . The MVC framework provides a clean
separation of the UI, Business Logic, Model or Data.
More Control
The ASP.NET MVC framework provides more control over HTML, JavaScript and CSS than the traditional Web
Forms.
Testability
ASP.NET MVC framework provides better testability of the Web Application and good support for the test driven
development too.
Lightweight
ASP.NET MVC framework doesn’t use View State and thus reduces the bandwidth of the requests to an extent.
One of the key advantages of using ASP.NET MVC is that it is built on top of ASP.NET framework and hence most of
the features of the ASP.NET like membership providers, roles, etc can still be used.
Creating a Simple Application Using MVC 4.0
The request object creation has four major steps. The following is the detailed explanation of the same.
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.
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.
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.
This phase has two steps executing the action and finally sending the response as a result to the view.
ASP.Net MVC Life Cycle
1. ViewResult (View): This return type is used to return a webpage from an action method.
2. PartialviewResult (Partialview): This return type is used to send a part of a view which will be rendered in
another view.
3. RedirectResult (Redirect): This return type is used to redirect to any other controller and action method
depending on the URL.
4. RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is used when we want to
redirect to any other action method.
5. ContentResult (Content): This return type is used to return HTTP content type like text/plain as the result
of the action.
6. jsonResult (json): This return type is used when we want to return a JSON message.
7. javascriptResult (javascript): This return type is used to return JavaScript code that will run in browser.
8. FileResult (File): This return type is used to send binary output in response.
9. EmptyResult: This return type is used to return nothing (void) in the result.
But many times we would like to perform some action before or after a particular operation. For achieving this
functionality, ASP.NET MVC provides feature to add pre and post action behaviors on controller's action methods.
Types of Filters:
Action filters are one of most commonly used filters to perform additional data processing, or manipulating the return
values or cancelling the execution of action or modifying the view structure at run time.
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.
Now we will see the code example to apply these filters on an example controller ActionFilterDemoController.
(ActionFilterDemoController is just used as an example. You can use these filters on any of your controllers.)
Output Cache
1. publicclassActionFilterDemoController: Controller
2. {
3. [HttpGet]
4. OutputCache(Duration = 10)]
5. publicstringIndex()
6. {
7. returnDateTime.Now.ToString("T");
8.
9. }
10. }
There are two types of routing (after the introduction of ASP.NET MVC 5).
1. Convention based routing: to define this type of routing, we call MapRoute method and set its unique
name, url pattern and specify some default values.
2. Attribute based routing: to define this type of routing, we specify the Route attribute in the action method
of the controller.
Routing is the URL pattern that is mappped together to a handler,rounting is responsible for incoming browser
request for particular MVC controller. In other ways let us say routing help you to define a URL structure and map the
URL with controller. There are three segments for routing that are important,
1. ControllerName
2. ActionMethodName
3. Parammeter
i.e: ControllerName/ActionMethodName/{ParamerName} and also route map coding written in a Global.asax file.
Routing in MVC
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.
Default Route
The default ASP.NET MVC project templates add a generic route that uses the following URL convention to break the
URL for a given request into three named segments.
URL: "{controller}/{action}/{id}"
This route pattern is registered via call to the MapRoute() extension method of RouteCollection.
Routing in MVC
ViewData
ViewBag
1. ViewBag is also used to pass data from the controller to the respective view.
2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
3. It is also available for the current request only.
4. If redirection occurs, then its value becomes null.
5. Doesn’t require typecasting for complex data type.
TempData
Partial view is a reusable view (like a user control) which can be embedded inside other view. For example, let’s say
all the pages of your site have a standard structure with left menu, header, and footer as in the following image,
Partial View in MVC
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.
With 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.
With MVC, you can create your own helpers, or use the built in HTML helpers.
HTML Links:
The easiest way to render an HTML link in is to use the HTML.ActionLink() helper.With MVC, the Html.ActionLink()
does not link to a view. It creates a link to a controller action.
ASP Syntax:
The first parameter is the link text, and the second parameter is the name of the controller action.
Property Description.
.linkText The link text (label).
.actionName The target action.
.routeValues The values passed to the action.
.controllerName The target controller.
.htmlAttributes The set of attributes to the link.
.protocol The link protocol.
.hostname The host name for the link.
.fragment The anchor target for the link.
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()
1. <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
2. <% using (Html.BeginForm()){%>
3. <p>
4. <label for="FirstName">First Name:</label>
5. <%= Html.TextBox("FirstName") %>
6. <%= Html.ValidationMessage("FirstName", "*") %>
7. </p>
8. <p>
9. <label for="LastName">Last Name:</label>
10. <%= Html.TextBox("LastName") %>
11. <%= Html.ValidationMessage("LastName", "*") %>
12. </p>
13. <p>
14. <label for="Password">Password:</label>
15. <%= Html.Password("Password") %>
16. <%= Html.ValidationMessage("Password", "*") %>
17. </p>
18. <p>
19. <label for="Password">Confirm Password:</label>
20. <%= Html.Password("ConfirmPassword") %>
21. <%= Html.ValidationMessage("ConfirmPassword", "*") %>
22. </p>
23. <p>
24. <label for="Profile">Profile:</label>
25. <%= Html.TextArea("Profile", new {cols=60, rows=10})%>
26. </p>
27. <p>
28. <%= Html.CheckBox("ReceiveNewsletter") %>
29. <label for="ReceiveNewsletter" style="display:inline">Receive Newsletter?</label>
30. </p>
31. <p>
32. <input type="submit" value="Register" />
33. </p>
34. <%}%>
In ASP.NET MVC 5.0 we have a new attribute route,cBy 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".
TempData is able to keep data for the duration of a HTP request, in other words it can keep live data between two
consecutive HTTP requests. It will help us to pass the state between action methods. TempData only works with the
current and subsequent request. TempData uses a session variable to store the data. TempData Requires type
casting when used to retrieve data.
Example
ASP.NET MVC has always supported the concept of "view engines" - which are the pluggable modules that
implement different template syntax options. The "default" view engine for ASP.NET MVC uses the same
.aspx/.ascx/. master file templates as ASP.NET Web Forms. Other popular ASP.NET MVC view engines are
Spart&Nhaml.
Why is Razor?
Razor View Engine ASPX View Engine (Web form view engine)
The namespace used by the Razor View The namespace used by the ASPX View Engine is
Engine is System.Web.Razor System.Web.Mvc.WebFormViewEngine
The file extensions used by the Razor View
The file extensions used by the Web Form View Engines are like
Engine are different from a web form view
ASP.Net web forms. It uses the ASPX extension to view the aspc
engine. It uses cshtml with C# and vbhtml
extension for partial views or User Controls or templates and master
with vb for views, partial view, templates and
extensions for layout/master pages.
layout pages.
The Razor View Engine is an advanced view
A web form view engine is the default view engine and available from
engine that was introduced with MVC 3.0.
the beginning of MVC
This is not a new language but it is markup.
Razor has a syntax that is very compact and The web form view engine has syntax that is the same as an ASP.Net
helps us to reduce typing. forms application.
The Razor View Engine uses @ to render The ASPX/web form view engine uses "<%= %>" or "<%: %>" to
server-side content. render server-side content.
By default all text from an @ expression is
There is a different syntax ("<%: %>") to make text HTML encoded.
HTML encoded.
Razor does not require the code block to be
closed, the Razor View Engine parses itself A web form view engine requires the code block to be closed properly
and it is able to decide at runtime which is a otherwise it throws a runtime exception.
content element and which is a code element.
The Razor View Engine prevents Cross Site
A web form View engine does not prevent Cross Site Scripting (XSS)
Scripting (XSS) attacks by encoding the script
attack.
or HTML tags before rendering to the view.
Web Form view engine does not support Test Driven Development
The Razor Engine supports Test Driven
(TDD) because it depends on the System.Web.UI.Page class to make
Development (TDD).
the testing complex.
Razor uses "@* … *@" for multiline The ASPX View Engine uses "<!--...-->" for markup and "/* … */" for
comments. C# code.
There is only three transition characters with
There are only three transition characters with the Razor View Engine.
the Razor View Engine.
The Razor View Engine is a bit slower than the ASPX View Engine.
Conclusion
Razor provides a new view engine with streamlined code for focused templating. Razor's syntax is very compact and
improves readability of the markup and code. By default MVC supports ASPX (web forms) and Razor View Engine.
MVC also supports third-party view engines like Spark, Nhaml, NDjango, SharpDOM and so on. ASP.NET MVC is
open source.
C# Example:
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:
1. <system.web>
2. <authenticationmode="Forms">
3. <formsloginUrl="Login.aspx" protection="All" timeout="30" name=".ASPXAUTH" path="/" requireSSL="
false" slidingExpiration="true" defaultUrl="default.aspx" cookieless="UseDeviceProfile" enableCrossAppRe
directs="false" />
4. </authentication>
5. </system.web>
The FormsAuthentication class creates the authentication cookie automatically when SetAuthCookie() or
RedirectFromLoginPage() methods are called. The value of authentication cookie contains a string representation of
the encrypted and signed FormsAuthenticationTicket object.
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 theGlobal.asax file that
can automatically find the area routes in the AreaRegistration file.
AreaRegistration.RegisterAllAreas();
1. Allows us to organize models, views and controllers into separate functional sections of the application, such
as administration, billing, customer support and much more.
2. Easy to integrate with other Areas created by another.
3. Easy for unit testing.
DisplayModes give you another level of flexibility on top of the default capabilities we saw in the last section.
DisplayModes can also be used along with the previous feature so we will simply build off of the site we just created.
1. We should register Display Mode with a suffix for particular browser using “DefaultDisplayMode”e class
inApplication_Start() method in the Global.asax file.
2. View name for particular browser should be appended with suffix mentioned in first step.
1. Desktop browsers (without any suffix. e.g.: Index.cshtml, _Layout.cshtml).
2. Mobile browsers (with a suffix “Mobile”. e.g.: Index.Mobile.cshtml,Layout.Mobile.cshtml)
If you want design different pages for different mobile device browsers (any different browsers) and render
them depending on the browser requesting. To handle these requests you can register custom display
modes. We can do that using DisplayModeProvider.Instance.Modes.Insert(int index, IDisplayMode item)
method.
ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio 2013 includes
pre-installed code generators for MVC and Web API projects. You add scaffolding to your project when you want to
quickly add code that interacts with data models. Using scaffolding can reduce the amount of time to develop
standard data operations in your project.
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.
Scaffolding Templates:
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.
Routing is a great feature of MVC, it provides a REST based URL that is very easy to remember and improves page
ranking in search engines.
This article is not an introduction to Routing in MVC, but we will learn a few features of routing and by implementing
them we can develop a very flexible and user-friendly application. So, let's start without wasting valuable time.
This is very necessary for when we want to add a specific constraint to our URL. Say, for example we want a 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:
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.
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.
Let's take an example. My MVC application displays a list of database records on the view page so by default each
time the user invokes the controller method to see records, the application loops through the entire process and
executes the database query. And this can actually decrease the application performance. So, we can advantage of
the "Output Caching" that avoids executing database queries each time the user invokes the controller method. Here
the view page is retrieved from the cache instead of invoking the controller method and doing redundant work.
In the above paragraph I said, in Output Caching the view page is retrieved from the cache, so where is the content
cached/stored?
Please note, there is no guarantee that content will be cached for the amount of time that we specify. When memory
resources become low, the cache starts evicting content automatically.
OutputCache label has a "Location" attribute and it is fully controllable. Its default value is "Any", however there are
the following locations available; as of now, we can use any one.
1. Any
2. Client
3. Downstream
4. Server
5. None
6. ServerAndClient
With "Any", the output cache is stored on the server where the request was processed. The recommended store
cache is always on the server very carefully. You will learn about some security related tips in the following "Don't use
Output Cache".
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.
The ValidationSummary helper method generates an unordered list (ul element) of validation messages that are in
the ModelStateDictionary object.
The ValidationSummary can be used to display all the error messages for all the fields. It can also be used to display
custom error messages. The following figure shows how ValidationSummary displays the error messages.
ValidationSummary() Signature:
By default, ValidationSummary filters out field level error messages. If you want to display field level error messages
as a summary then specify excludePropertyErrors = false.
So now, the following Edit view will display error messages as a summary at the top. Please make sure that you don't
have a ValidationMessageFor method for each of the fields.
Understanding Validation In MVC - Part 4
Database First Approach is an alternative to the Code First and Model First approaches to the Entity Data Model
which creates model codes (classes,properties, DbContextetc) from the database in the project and that classes
behaves as the link between database and controller.
There are the following approach which is used to connect with database to application.
Database First
Model First
Code First
Database first is nothing but only a approach to create web application where database is available first and can
interact with the database. In this database, database is created first and after that we manage the code. The Entity
Framework is able to generate a business model based on the tables and columns in a relational database.
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 retrived 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.
Exception handling may be required in any application, whether it is a web application or a Windows Forms
application.
ASP.Net MVC has an attribute called "HandleError" that provides built-in exception filters. The HandleError attribute
in ASP.NET MVC can be applied over the action method as well as Controller or at the global level. The HandleError
attribute is the default implementation of IExceptionFilter. When we create a MVC application, the HandleError
attribute is added within the Global.asax.cs file and registered in the Application_Start event.
The HandleError Error attribute has a couple for properties that are very useful in handling the exception.
ExceptionType: Type of exception to be catch. If this property is not specified then the HandleError filter handles all
exceptions.
View: Name of the view page for displaying the exception information.
Order:
Order in which the action filters are executed. The Order property has an integer value and it specifies the priority
from 1 to any positive integer value. 1 means highest priority and the greater the value of the integer is, the lower is
the priority of the filter.
AllowMultiple: It indicates whether more than one instance of the error filter attribute can be specified.
Example
1. [HandleError(View = "Error")]
2. public class HomeController: Controller
3. {
4. public ActionResult Index()
5. {
6. ViewBag.Message = "Welcome to ASP.NET MVC!";
7. int u = Convert.ToInt32(""); // Error line
8. return View();
9. }
10. }
1. [HandleError(View = "Error")]
2. public ActionResult Index()
3. {
4. ViewBag.Message = "Welcome to ASP.NET MVC!";
5. int u = Convert.ToInt32(""); // Error line
6. return View();
7. }
ViewData
ViewBag
ViewBag is just a dynamic wrapper around ViewData and exists only in ASP.NET MVC 3. 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 types.
ViewBag also contain a null value when redirection occurs.
TempData
Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio 2013 includes pre-installed
code generators for MVC and Web API projects. You add scaffolding to your project when you want to quickly add
code that interacts with data models. Using scaffolding can reduce the amount of time to develop standard data
operations in your project.
Prerequisites:
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:
1. @ {
2. Layout = "~/Views/Shared/_v1.cshtml";
3. } < !DOCTYPE html >
4. < html >
5. < head >
6. < meta name = "viewport"
7. content = "width=device-width" / >
8. < title > ViewStart < /title> < /head> < body >
9. < /body> < /html>
ViewBag is dynamic property that takes advantage of new dynamic features in C# 4.0. It's also used to pass data
from a controller to a view. In short, The ViewBag property is simply a wrapper around the ViewData that exposes the
ViewData dictionary as a dynamic object. Now create an action method "StudentSummary" in the
"DisplayDataController" controller that stores a Student class object in ViewBag.
Thereafter create a view StudentSummary ("StudentSummary.cshtml") that shows student object data. ViewBag
does not require typecasting for complex data type so you can directly access the data from ViewBag.
1. @ {
2. ViewBag.Title = "Student Summary";
3. var student = ViewBag.Student;
4. }
5. < table >
6. < tr >
7. < th > Name < /th> < th > Age < /th> < th > City < /th> < /tr> < tr >
8. < td > @student.Name < /td> < td > @student.Age < /td> < td > @student.City < /td> < /tr>
9. < /table>
Here we used one more thing, "ViewBag.Title", that shows the title of the page.
ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using
strings as keys.
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
ViewData requires typecasting for complex data type and check for null values to avoid error.
ViewBag doesn't require typecasting for complex data type.
Calling of ViewBag is:
ViewBag.Name = "Yogesh";
Calling of ViewDatais :
ViewData["Name"] = "yogesh";
DataAnnotation plays a vital role in added validation to properties while designing the model itself. This validation can
be added for both the client side and the server side.
You understand that decorating the properties in a model with an Attribute can make that property eligible for
Validation.
1. Required
2. RegularExpression
3. Range
Specifies the Range of values between which the property values are checked.
1. [Range(1000,10000,ErrorMessage="Range should be between 1k & 10k")]
4. StringLength
5. MaxLength
6. MinLength
The HandleErrorAttribute allows you to use a custom page for this error. First you need to update your web.config file
to allow your application to handle custom errors.
1. <system.web>
2. <customErrors mode="On">
3. </system.web>
1. [HandleError]
2. public class HomeController: Controller
3. {
4. [HandleError]
5. publicActionResultThrowException()
6. {
7. throw new ApplicationException();
8. }
9. }
By calling the ThrowException action, this would then redirect the user to the default error page. In our case though,
we want to use a custom error page and redirect the user there instead.So, let's create our new custom view page.
Next, we simply need to update the HandleErrorAttribute on the action method.
1. [HandleError]
2. public class HomeController: Controller
3. {
4. [HandleError(View = "CustomErrorView")]
5. publicActionResultThrowException()
6. {
7. throw new ApplicationException();
8. }
9. }
The ASP.NET MVC Framework validates any data passed to the controller action that is executing, It populates a
ModelState object with any validation failures that it finds and passes that object to the controller. Then the controller
actions can query the ModelState to discover whether the request is valid and react accordingly.
I will use two approaches in this article to validate a model data. One is to manually add an error to the ModelState
object and another uses the Data Annotation API to validate the model data.
1. namespace ServerValidation.Models
2. {
3. public class User
4. {
5. public string Name
6. {
7. get;
8. set;
9. }
10. public string Email
11. {
12. get;
13. set;
14. }
15. }
16. }
After that I create a controller action in User Controller (UserController.cs under Controllers folder). That action
method has logic for the required validation for Name and Email validation on the Email field. I add an error message
on ModelState with a key and that message will be shown on the view whenever the data is not to be validated in the
model.
1. using System.Text.RegularExpressions;
2. using System.Web.Mvc;
3. namespace ServerValidation.Controllers
4. {
5. public class UserController: Controller
6. {
7. public ActionResult Index()
8. {
9. return View();
10. }
11. [HttpPost]
12. public ActionResult Index(ServerValidation.Models.User model)
13. {
14.
15. if (string.IsNullOrEmpty(model.Name))
16. {
17. ModelState.AddModelError("Name", "Name is required");
18. }
19. if (!string.IsNullOrEmpty(model.Email))
20. {
21. string emailRegex = @ "^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
22. @ "\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
23. @ ".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
24. Regex re = new Regex(emailRegex);
25. if (!re.IsMatch(model.Email))
26. {
27. ModelState.AddModelError("Email", "Email is not valid");
28. }
29. } else {
30. ModelState.AddModelError("Email", "Email is required");
31. }
32. if (ModelState.IsValid)
33. {
34. ViewBag.Name = model.Name;
35. ViewBag.Email = model.Email;
36. }
37. return View(model);
38. }
39. }
40. }
Thereafter I create a view (Index.cshtml) for the user input under the User folder.
1. @model ServerValidation.Models.User
2. @ {
3. ViewBag.Title = "Index";
4. }
5. @using(Html.BeginForm())
6. {
7. if (@ViewData.ModelState.IsValid)
8. {
9. if (@ViewBag.Name != null)
10. { < b >
11. Name: @ViewBag.Name < br / >
12. Email: @ViewBag.Email < /b>
13. }
14. } < fieldset >
15. < legend > User < /legend> < div class = "editor-label" >
16. @Html.LabelFor(model => model.Name) < /div> < div class = "editor-field" >
17. @Html.EditorFor(model => model.Name)
18. @if(!ViewData.ModelState.IsValid)
19. {
20. < span class = "field-validation-
error" > @ViewData.ModelState["Name"].Errors[0].ErrorMessage < /span>
21.
22. }
23. < /div> < div class = "editor-label" >
24.
25. @Html.LabelFor(model => model.Email) < /div> < div class = "editor-field" >
26. @Html.EditorFor(model => model.Email)
27. @if(!ViewData.ModelState.IsValid)
28. {
29. < span class = "field-validation-
error" > @ViewData.ModelState["Email"].Errors[0].ErrorMessage < /span>
30. }
31. < /div> < p >
32. < input type = "submit"
33. value = "Create" / >
34. < /p> < /fieldset>
35. }
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, whetehr 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.
Practical Explanation
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:
Exception are part and parcel of an application. They are a boon and a ban for an application too. Isn't it? This would
be controversial, for developers it helps them track minor and major defects in an application and sometimes they are
frustrating when it lets users land on the Yellow screen of death each time. This would make the users mundane to
the application. Thus to avoid this, developers handle the exceptions. But still sometimes there are a few unhandled
exceptions.
Now what is to be done for them? MVC provides us with built-in "Exception Filters" about which we will explain here.
cc: Google
Let's start!
Get Started
Exception filters run when some of the exceptions are unhandled and thrown from an invoked action. The reason for
the exception can be anything and so is the source of the exception.
Custom Exception Filters must implement the builtinIExceptionFilter interface. The interface looks as in the following:
Whenever an unhandled exception is encountered, the OnException method gets invoked. The parameter as we can
see, ExceptionContext is derived from the ControllerContext and has a number of built-in properties that can be used
to get the information about the request causing the exception. Their property's ExceptionContextpassess are shown
in the following table:
The exception being thrown from the action is detailed by the Exception property and once handled (if), then the
property ExceptionHandled can be toggled, so that the other filters would know if the exception has been already
handled and cancel the other filter requests to handle. The problem is that if the exceptions are not handled, then the
default MVC behavior shows the dreaded yellow screen of death. To the users, that makes a very impression on the
users and more importantly, it exposes the application's handy and secure information to the outside world that may
have hackers and then the application gets into the road to hell. Thus, the exceptions need to be dealt with very
carefully. Let's show one small custom exception filter. This filter can be stored inside the Filters folder in the web
project of the solution. Let's add a file/class called CustomExceptionFilter.cs.
Helper methods are used to render HTML in the view. Helper methods generates HTML output that is part of the
view. They provide an advantage over using the HTML elements since they can be reused across the views and also
requires less coding. There are several builtin helper methods that are used to generate the HTML for some
commonly used HTML elements, like form, checkbox, dropdownlist etc. Also we can create our own helper methods
to generate custom HTML. First we will see how to use the builtin helper methods and then we will see how to create
custom helper methods.
The controller provides model data to the view, and interprets user actions such as button clicks. The controller
depends on the view and the model. In some cases, the controller and the view are the same object.
In our example, Visual Web Developer has created the following files: HomeController.cs (for the Home and About
pages) and AccountController.cs (For the Log On pages):
The model represents the data, and does nothing else. The model does NOT depend on the controller or the
view. The MVC Model contains all application logic (business logic, validation logic, and data access logic), except
pure view and controller logic. With MVC, models both hold and manipulate application data.
The Models Folder contains the classes that represent the application model.
Visual Web Developer automatically creates an AccountModels.cs file that contains the models for application
security.
A view is responsible for displaying all of, or a portion of, data for users. In simple terms, whatever we see on the
output screen is a view.
The Views folder contains one folder for each controller. Visual Web Developer has created an Account folder, a
Home folder, and a Shared folder (inside the Views folder). The Account folder contains pages for registering and
logging in to user accounts. The Home folder is used for storing application pages like the home page and the about
page. The Shared folder is used to store views shared between controllers (master pages and layout pages).
A route attribute is defined on top of an action method. The following is the example of a Route Attribute in which
routing is defined where the action method is defined.
In the following example, I am defining the route attribute on top of the action method
We can also define an optional parameter in the URL pattern by defining a question mark (“?") to the route
parameter. We can also define the default value by using parameter=value.
RenderSection() is a method of the WebPageBase class. Scott wrote at one point, The first parameter to the
"RenderSection()" helper method specifies the name of the section we want to render at that location in the layout
template. The second parameter is optional, and allows us to define whether the section we are rendering is required
or not. If a section is "required", then Razor will throw an error at runtime if that section is not implemented within a
view template that is based on the layout file (that can make it easier to track down content errors). It returns the
HTML content to render.
1. <div id="body">
2. @RenderSection("featured", required: false)
3. <section class="content-wrapper main-content clear-fix">
4. @RenderBody()
5. </section>
6. </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.
In MVC 6 Microsoft removed the dependency of System.Web.Dll from MVC6 because it's so expensive that typically
it consume 30k of memory per request and response, whereas now MVC 6 only requires 2k of memory per request
and the response is a very small memory consumtion.
The advantage of using the cloud-optimized framework is that we can include a copy of the mono CLR with your
website. For the sake of one website we do not need to upgrade the .NET version on the entire machine. A different
version of the CLR for a different website running side by side.
MVC 6 is a part of ASP.NET 5 that has been designed for cloud-optimized applications. The runtime automatically
picks the correct version of the library when our MVC application is deployed to the cloud.
The Core CLR is also supposed to be tuned with a high resource-efficient optimization.
Microsoft has made many MVC, Web API, WebPage and SignalLrpeices we call MVC 6.
Most of the problems are solved using the Roslyn Compiler. In ASP.NET vNext uses the Roslyn Compiler. Using the
Roslyn Compiler we do not need to compile the application, it automatically compiles the application code. You will
edit a code file and can then see the changes by refreshing the browser without stopping or rebuilding the project.
Where we use MVC5 we can host it on an IIS server and we can also run it on top of an ASP. NET Pipeline, on the
other hand MVC 6 has a feature that makes it better and that feature is itself hosted on an IIS server and a self-user
pipeline.
The configuration system provides an environment to easily deploy the application on the cloud. Our application
works just like a configuration provider. It helps to retrieve the value from the various configuration sources like XML
file.
MVC 6 includes a new environment-based configuration system. Unlike something else it depends on just the
Web.Config file in the previous version.
Dependency injection
Using the IServiceProvider interface we can easily add our own dependency injection container. We can replace the
default implementation with our own container.
Supports OWIN
We have complete control over the composable pipeline in MVC 6 applications. MVC 6 supports the OWIN
abstraction.