Core MVC
Core MVC
NET MVC
interview questions. MVC is the framework used to build Web applications for .NET and C#. In
this article, I list the top 50 MVC questions and their answers. The answers are code examples
written by authors of C# Corner
MVC is a framework for building web applications using an 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.
Due to the separation of the model from the view, the user interface can display multiple views
of the same data at the same time.
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.
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 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 the ASP.NET
framework and hence most of the features of the ASP.NET like membership providers, roles, etc
can still be used.
3. Explain MVC application life cycle?
Any web application has two main execution steps, first understanding the request and
depending on the type of the request sending out an 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.
The request object creation has four major steps. The following is a 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 rout table with routes
collection. This filling of the route table happens 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 phase has two steps executing the action and finally sending the response as a result to
the view.
There are total of nine return types we can use to return results from the controller to view.
ViewResult (View)
PartialviewResult (Partialview)
This return type is used to send a part of a view that 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.
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)
javascriptResult (javascript)
This return type is used to return JavaScript code that will run in the browser.
FileResult (File)
But many times we would like to perform some action before or after a particular
operation. For achieving this functionality, ASP.NET MVC provides a feature to add pre
and post-action behaviors on the controller's action methods.
Types of Filters
● Action Filters
Action filters are used to implement logic that gets executed before and after a
controller action executes. We will look at Action Filters in detail in this chapter.
● Authorization Filters
● Result Filters
Result filters contain logic that is executed before and after a view result is
executed. For example, you might want to modify a view result right before the
view is rendered to the browser.
● Exception Filters
Exception filters are the last type of filter to run. You can use an exception filter to
handle errors raised by either your controller actions or controller action results.
You can also use exception filters to log errors.
Action filters are one of the most commonly used filters to perform additional data
processing, or manipulating the return values or canceling the execution of an 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
Code Example
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. ControllerName
2. ActionMethodName
3. Parammeter
Code Example
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 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 a call to the MapRoute() extension method of
RouteCollection.
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. It doesn’t require typecasting for the complex data type.
TempData
A partial view is a chunk of HTML that can be safely inserted into an existing DOM. Most
commonly, partial views are used to componentize Razor views and make them easier to build
and update. Partial views can also be returned directly from controller methods. In this case, the
browser still receives text/html content but not necessarily HTML content that makes up an
entire page. As a result, if a URL that returns a partial view is directly invoked from the address
bar of a browser, an incomplete page may be displayed. This may be something like a page that
misses title, script and style sheets. However, when the same URL is invoked via a script, and
the response is used to insert HTML within the existing DOM, then the net effect for the
end-user may be much better and nicer.
Partial view is a reusable view (like a user control) which can be embedded inside another 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,
11. Explain what is the difference between View and
Partial View?
View
Partial View
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()
ASP.NET Syntax C#
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. <%}%>
Example
Why is Razor?
Razor View Engine ASPX View Engine (Web form view engine)
The namespace used by the Razor The namespace used by the ASPX View Engine is
View Engine is System.Web.Razor System.Web.Mvc.WebFormViewEngine
By default all text from an @ There is a different syntax ("<%: %>") to make text HTML
expression is HTML encoded. encoded.
Razor uses "@* … *@" for The ASPX View Engine uses "<!--...-->" for markup and "/*
multiline comments. … */" for C# code.
The Razor View Engine is a bit slower than the ASPX View Engine.
Conclusion
Razor provides a new view engine with a streamlined code for focused templating.
Razor's syntax is very compact and improves the 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.
17. What are the Main Razor Syntax Rules?
Answer
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" ena
bleCrossAppRedirects="false" />
4. </authentication>
5. </system.web>
Answer
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 theGlobal.asax file that can automatically
find the area routes in the AreaRegistration file.
AreaRegistration.RegisterAllAreas();
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.
Answer
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.
Answer
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:
Answer
ASP.NET MVC has always supported the concept of "view engines" that are the pluggable
modules that implement various template syntax options. The "default" view engine for
ASP.NET MVC uses the same .aspx/.ascx/.master file templates as ASP.NET Web Forms. In
this article I go through the Razor View Engine to create a view of an application. "Razor" was in
development beginning in June 2010 and was released for Microsoft Visual Studio in January
2011.
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".
Answer
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.
26. What is Validation Summary in MVC?
Answer
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.
Example - ValidationSummary to display field errors
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.
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
View and logic are separate, it has separation of No separation of concerns; Views are
concerns theory. MVC 3 onwards has .aspx page as tightly coupled with logic (.aspx.cs /.vb
.cshtml. file).
Introduced concept of routing for route based URL. File-based routing .Redirection is based
Routing is declared in Global.asax for example. on pages.
Support Razor syntax as well as .aspx Support web forms syntax only.
Multiple pages can have the same controller to Each page has its own code, in other
satisfy their requirements. A controller may have words direct dependency on code. For
multiple Actions (method name inside the controller example Sachin.aspx is dependent on
class). Sachin.aspx.cs (code behind) file.
Unit Testing is quite easier than ASP.Net Web forms Direct dependency, tight coupling raises
Since a web form and code are separate files. issues in testing.
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.
ExceptionType
Type of exception to be catch. If this property is not specified then the HandleError filter
handles all exceptions.
View
Master
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. }
There are three options in Model View Controller (MVC) for passing data from controller
to view. This article attempts to explain the differences among ViewData, ViewBag and
TempData with examples. ViewData and ViewBag are similar and TempData performs
additional responsibility. The following are the key points on those three objects.
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
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>
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.
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.
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.
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(ErrorMessage="CustomerName is mandatory")]
2. RegularExpression
3. Range
Specifies the Range of values between which the property values are checked.
4. StringLength
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.
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.
I create a User class under the Models folder. The User class has two properties
"Name" and "Email". The "Name" field has required field validations while the "Email"
field has Email validation. So let's see the procedure to implement the validation. Create
the User Model as in the following,
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. }
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 requ
ired");
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 i
s not valid");
28. }
29. } else {
30. ModelState.AddModelError("Email", "Email is re
quired");
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-labe
l" >
16. @Html.LabelFor(model => model.Name) < /div> < div clas
s = "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 cla
ss = "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 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.
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.
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.
Answer
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.
The Controllers Folder
The Controllers Folder contains the controller classes responsible for handling user input and
responses. MVC requires the name of all controllers to end with "Controller".
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):
Answer
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.
Answer
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 stores the files (HTML files) related to the display of the application (the user
interfaces). These files may have the extensions html, asp, aspx, cshtml, and vbhtml, depending
on the language content.
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).
47. What is Attribute Routing in MVC?
Answer
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 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>
Answer
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.
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.
Answer
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.
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.
What is an ORM, and why would you use one instead of plain old
ADO.NET?
Hide answer
An ORM is an object relational mapping framework. Such a framework can help to
reduce the amount of handwritten code in a typical web application. ORM can be used
when there are no extreme requirements for performance in an application, but there
are some frameworks (e.g., Dapper) which can be used even in high-load systems.
[ASP.NET Core MVC] You have a CategoriesController and an Add action with the
next signature looking like this:
[HttpPost]
public IActionResult Add(NewCategoryModel model)
You have to explicitly specify that the parameter model should be extracted from a
request body. How would you achieve that?
Hide answer
Add [FromBody] like so:
[HttpPost]
public IActionResult Add([FromBody]NewCategoryModel model)
Step 1: We need to add a custom global route (usually in Startup.cs) before the
default one:
routes.MapRoute(
name: "v2",
template: "v2/{controller}/{action=ShowAll}"
);
Steps:
[HttpGet]
[Route("v2/[controller]")]
public IActionResult ShowAll()
{
return View();
}
[HttpPost]
[Route("v2/[controller]/[action]")]
public IActionResult Add()
{
return View();
}
This is a good decision if you have specific requirements for a URL scheme, e.g., a
REST API.
Option #3: Configure a base route on a controller level and relative routes on an action
level.
Steps:
[Route("v2/[controller]")]
public class CategoriesController : Controller
{
[HttpGet]
[Route("")]
public IActionResult ShowAll()
{
return View();
}
[HttpPost]
[Route("[action]")]
public IActionResult Add()
{
return View();
}
// ...
This is also a good decision if you have specific requirements for a URL scheme. In fact, it can
be a better option than the previous one if you always have a constant string or a controller
name as a prefix for your routes.
In ASP.NET MVC 5:
To intercept exceptions globally, the filter should be registered
in GlobalFilterCollection (usually in ~/App_Start/FilterConfig). Authentication,
authorization, custom action filters, logging, and action result transformation can be
done with the same approach.
● Objects are not responsible for creating services and providing dependencies.
Hide answer
In the Web.config file (in the root folder of your application)
set sessionState to StateServer for shared in-memory storage or SQLServer for
shared durable storage.
Hide answer
There are several answers, because ASP.NET Core is a new platform and supports
several approaches. The candidate has to stress that, in the project, we need to use
some kind of distributed cache—for example, Redis. Also, Microsoft provides several
packages to help with this. In the case of
Redis, Microsoft.Extensions.Caching.Redis provides the middleware and
implements IDistributedCache to provide a standardized way to work with it.
What is the difference between asynchronous and
synchronous actions? When would you use asynchronous
actions?
Hide answer
Asynchronous actions won’t block the executing thread if it waits for an I/O operation.
Using asynchronous actions can increase the throughput of a system if you use such a
pattern for I/O operations, but it won’t help with CPU-bound operations.
RenderAction will call an action method of the current controller and render a result inline. In
contrast, RenderPartial will render the specified view inline without calling any action method.
Razor is the first major update to render HTML in ASP.Net MVC 3. Razor was designed
specifically for view engine syntax. Main focus of this would be to simplify and code-focused
templating for HTML generation. Below is the sample of using Razor:
@model ASP.Net MVCMusicStore.Models.Customer
@{ViewBag.Title = "Get Customers";}
< div class="cust"> <h3><em>@Model.CustomerName</<em> </<h3><div>
● System.Web.ASP.Net MVC
● System.Web.ASP.Net MVC.Ajax
● System.Web.ASP.Net MVC.Html
● System.Web.ASP.Net MVC.Async
What is ViewData?
Viewdata contains the key, value pairs as dictionary and this is derived from class :
"ViewDataDictionary". In action method we are setting the value for viewdata and in view the
value will be fetched by typecasting.
● ViewResult
● PartialViewResult
● RedirectToRouteResult
● RedirectResult
● JavascriptResult
● JSONResult
● FileResult
● HTTPStatusCodeResult
● Empty
● Create
● Delete
● Details
● Edit
● List
Can a view be shared across multiple controllers? If Yes, How we can do that?
Yes we can share a view across multiple controllers. We can put the view in the "Shared" folder.
When we create a new ASP.Net MVC Project we can see the Layout page will be added in the
shared folder, which is because it is used by multiple child pages.
● Html.Partial()
● Html.RenderPartial()
Mention some action filters which are used regularly in ASP.Net MVC?
Below are some action filters used :
● Authentication
● Authorization
● HandleError
● OutputCache
How can we determine action invoked from HTTP GET or HTTP POST?
This can be done in following way : Use class : "HttpRequestBase" and use the method :
"HttpMethod" to determine the action request type.
In Server how to check whether model has error or not in ASP.Net MVC?
Whenever validation fails it will be tracked in ModelState. By using property : IsValid it can be
determined. In Server code, check like this :
if(ModelState.IsValid){
// No Validation Errors
}
Does Tempdata hold the data for other request in ASP.Net MVC?
If Tempdata is assigned in the current request then it will be available for the current request and
the subsequent request and it depends whether data in TempData read or not. If data in
Tempdata is read then it would not be available for the subsequent requests.
● NUnit
● xUnit.NET
● Ninject 2
● Moq
What is Representational State Transfer (REST) mean?
REST is an architectural style which uses HTTP protocol methods like GET, POST, PUT, and
DELETE to access the data. ASP.Net MVC works in this style. In ASP.Net MVC 4 there is a
support for Web API which uses to build the service using HTTP verbs.
What are the differences between Partial View and Display Template and Edit
Templates in ASP.Net MVC?
● Display Templates : These are model centric. Meaning it depends on the properties of the
view model used. It uses convention that will only display like divs or labels.
● Edit Templates : These are also model centric but will have editable controls like
Textboxes.
● Partial View : These are view centric. These will differ from templates by the way they
render the properties (Id's) Eg : CategoryViewModel has Product class property then it
will be rendered as Model.Product.ProductName but in case of templates if we
CategoryViewModel has List then @Html.DisplayFor(m => m.Products) works and it
renders the template for each item of this list.
In an MVC model,
● View Result
● Javascript Result
● Redirect Result
● Json Result
● Content Result
In MVC " ActionFilters" help you to execute logic while MVC action is
executed or its executing.
12) Explain what are the steps for the execution of an MVC project?
13) Explain what is routing? What are the three segments for routing is
important?
Routing helps you to decide a URL structure and map the URL with the
Controller.
● ControllerName
● ActionMethodName
● Parameter
15) Explain using hyperlink how you can navigate from one view to other
view?
By using "ActionLink" method as shown in the below code. The below code
will make a simple URL which help to navigate to the "Home" controller and
invoke the "GotoHome" action.
17) Mention what is the difference between Temp data, View, and View
Bag?
● Temp data: It helps to maintain data when you shift from one controller
to other controller.
● View data: It helps to maintain data when you move from controller to
view
● View Bag: It's a dynamic wrapper around view data
● Ajax libraries
● Jquery
21) Explain how you can send the result back in JSON format in MVC?
In order to send the result back in JSON format in MVC, you can use
"JSONRESULT" class.
22) Explain what is the difference between View and Partial View?
● It contains the layout page ● It does not contain the layout page
● Before any view is rendered, viewstart ● Partial view does not verify for a
page is rendered viewstart.cshtml. We cannot put
● View might have markup tags like common code for a partial view
body, html, head, title, meta etc.
● View is not lightweight as compare to within the viewStart.cshtml.page
Partial View
● Partial view is designed specially to
render within the view and just
because of that it does not consist
any mark up
In MVC, there are twelve types of results in MVC where "ActionResult" class
is the main class while the 11 are their sub-types
● ViewResult
● PartialViewResult
● EmptyResult
● RedirectResult
● RedirectToRouteResult
● JsonResult
● JavaScriptResult
● ContentResult
● FileContentResult
● FileStreamResult
● FilePathResult
All public methods of a controller class are treated as the action method if you
want to prevent this default method then you have to assign the public method
with NonActionAttribute.
This default route prevents request for a web resource file such as
Webresource.axd or ScriptResource.axd from being passed to the controller.
26) Mention the order of the filters that get executed, if the multiple
filters are implemented?
28) Mention what are the file extensions for razor views?
29) Mention what are the two ways for adding constraints to a route?
● As the code is moved behind a separate class file, you can use the
code to a great extent
● As behind code is simply moved to.NET class, it is possible to automate
UI testing. This gives an opportunity to automate manual testing and
write unit tests.
1. Mention what does Model-View-Controller represent
in an MVC application?
Components Description
MVC is an abbreviation for Model, View, and Controller. The MVC architectural
pattern separates an application into three components – Model, View, and Controller.
In this pattern, the model represents the shape of the data and business logic. It
maintains and preserves the data of the application. Model objects retrieve and store
model state in a database. The view is basically and technically a user interface. The
view segment displays the data-using model to the user and also enables them to
modify the data. The controller is the part, which handles the user request.
● Multiple view support: Because of the separation of the model from the view,
the user interface can display multiple views of the same data and at the same
time.
● Change Accommodation: User interfaces tend to change more frequently than
business rules.
● SoC – Separation of Concerns: 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 WebForms.
● Testability: This framework provides better testability of the Web Application and
good support for the test-driven development too.
● Lightweight: MVC framework doesn’t use View State and that reduces the
bandwidth of the requests to an extent.
The Model is the part of the application, which only handles the logic for the application
data. Regularly, the model objects retrieve data (as well as store data) from a database.
The View is the part of the application, which takes care of the display of the data. Most
often, the views are created from the model data, although there are other, more
complicated methods of creating views. The Controller, as the name implies, is the part
of the application that handles user interaction.
● App initialization
● Routing
● Instantiate and execute controller
● Locate and invoke controller action
● Instantiate and render view.
There are the following approaches, which are used to connect the database with the
application.
● Database First
● Model First
● Code First
URL: "{controller}/{action}/{id}"
This route pattern is registered via a call to the MapRoute() extension method
of RouteCollection.
POST Action Type: Tthe POST is used to submit data to be processed to a specified
resource. With all the POST requests, we pass the URL, which is essential and the
data. However, it can take up the following overloads.
21. How does View Data differ from View Bag in MVC?
View Data View Bag
ViewData is used to pass data from a ViewBag is also used to pass data from the
controller to view controller to the respective view.
It is also available for the current request
It is available for the current request only.
only.
Requires typecasting for complex data type Doesn’t require typecasting for the complex
and checks for null values to avoid error data type.
● Required
● DataType
● Range
● StringLength
● Ajax libraries
● Jquery
1 @TempData["MyData"];
2 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.
For satisfying the broad range of clients, REST was the proposed approach. WebAPI is
the technology by which you can expose data over HTTP following REST principles.
1 [NonAction]
3 // Method logic
4 }
We have also set the exception so that it can be displayed inside the view.
1
public class HomeController : Controller{
2
protected override void OnException(ExceptionContext filterContext){
3 Exception ex = filterContext.Exception;
4 filterContext.ExceptionHandled = true;
5 var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");
6 filterContext.Result = new ViewResult()
7 {
8 ViewName = "Error",
9 ViewData = new ViewDataDictionary(model)
10 };
}
11 }
12
1 @{
2 int x = 123;
3 string y = “aa”;
4 }
1 @Html.Partial(“TestPartialView”)
→Segregating the configs for MVC routing, Web API, Bundle etc.
→Mobile templates
→App initialization
→Routing
@model MvcMusicStore.Models.Customer
routes.IgnoareRoute(“{resource}.axd/{*pathInfo}”);
routes.MapMvcAttributeRoutes();
//convention-based routing
routes.MapRoute
name: “Default”,
url: “{controller}/{action}/{id}”,
System.Web.Mvc
System.Web.Mvc.Ajax
System.Web.Mvc.Html
System.Web.Mvc.Async
@{
Layout = “~/Views/Shared/TestLayout1.cshtml”;
}
This indicates child page uses TestLayout page as it’s master page.
@RenderSection(“TestSection”)
@section TestSection{
<h1>Test Content</h1>
If any child page does not have this section defined then error will
be thrown so to avoid that we can render the HTML like this –
This page is used to make sure common layout page will be used
for multiple views. Code written in this file will be executed first
when application is being loaded.
Below are the methods used to render the views from action -
PartialViewResult
RedirectToRouteResult
RedirectResult
JavascriptResult
JSONResult
FileResult
HTTPStatusCodeResult
[NonAction]
// Method logic
}
[ActionName(“TestActionNew”)]
return View();
@{
int x = 123;
string y = “aa”;
<script type=”text/javascript”>
function DrpIndexChanged() { }
</script>
@Html.Partial(“TestPartialView”)
Empty
Create
Delete
Details
Edit
List
Below are the two types of extensions razor view can have –
Html.Partial()
Html.RenderPartial()
No. We cannot add the test cases in Visual Studio Express edition
it can be added only in Professional and Ultimate versions of
Visual Studio.
50) What is the use .Glimpse in MVC?
Razor is a view engine that lets you embed server-based code into web pages using C#
and VB.Net. It was introduced in MVC 3 and a gneral purpose templating engine.
Routing is the process of monitoring the requests with the MVC application. In MVC,
the Application_Start() event registers all the routes in the routing table.
In ASP.NET MVC 5.0, a new type of routing is introduced, it is called Attribute Routing.
It enables the developers to define the routing using attributes on top of the controller
action method. To use the attribute routing in the MVC 5, you need to call the
MapMvcAttributeRoute method. The optional parameter for the URI can be added to the
route parameter using the question mark(?) in the attribute routing.
4) What is TempData in MVC?
The TempData in the ASP.NET MVC is used to store temporary data. It can be used in
subsequent requests. This TempData will be cleared after the completion of the
subsequent request. It is useful in transferring the non-sensitive data from one action
method to another action method of the same or a different controller and redirects. It
stores data as key-value pair.
Example
A partial view is a chunk of HTML that can be safely inserted into an existing DOM.
Most commonly, partial views are used to componentize Razor views and make them
easier to build and update. Partial views can also be returned directly from controller
methods. In this case, the browser still receives text/HTML content but not necessarily
HTML content that makes up an entire page. As a result, if a URL that returns a partial
view is directly invoked from the address bar of a browser, an incomplete page may be
displayed. This may be something like a page that misses title, script and style sheets.
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 the complex data type.
A route is a URL pattern that is mapped to a handler. The handler can be a physical file,
such as an .aspx file in 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.
Routing is a mechanism to process the incoming URL that is more descriptive and gives
the desired response. In this case, URL is not mapped to specific files or folder, as was
the case of websites in the past.
1. ControllerName
2. ActionMethodName
3. Parammeter
The filter in ASP.NET MVC is a class that is executed before or after an action method
is executed. It is a place where you can write custom logic that you want to execute. It
can be executed either to an action method or a controller. It is applied in two different
ways, declarative and programmatic. Applying the filter to the action or controller class
is called a declarative filter. Defining the interface for the filter is called the programmatic
way of applying a filter.
There are four types of built-in filters in ASP.NET MVC are authorization filter, action
filter, result filter, exception filter. These filters give an interface for which you can
define your custom filter.
An action filter is a type of filter in ASP.NET MVC that is executed to implement logic
before and after a controller is executed. These provide an additional attribute that is
applied to a section of the controller or the whole controller to modify it. These attributes
are defined under System.Attribute class.
● Output cache – It caches the output of a controller action. The output is cached here for
a defined amount of time.
● Handle Error – This filter is used to handle errors from the execution of controller action.
● Authorize – This filter is used to restrict access to the action method for a particular
user.
● Action Filters: Action filters are used to implement logic that gets executed before and
after a controller action executes. We will look at Action Filters in detail in this chapter.
● Authorization Filters: Authorization filters are used to implement authentication and
authorization for controller actions.
● Result Filters: Result filters contain logic that is executed before and after a view result
is executed. For example, you might want to modify a view result right before the view is
rendered to the browser.
● Exception Filters: Exception filters are the last type of filter to run. You can use an
exception filter to handle errors raised by either your controller actions or controller
action results. You can also use exception filters to log errors.
There is total of nine return types we can use to return results from a controller to view.
The base type of all these result types is ActionResult.
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 that
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 the 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.
Any web application has two main execution steps, first understanding the request and
depending on the type of the request sending out an 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.
● Multiple view support: Due to the separation of the model from the view, the user
interface can display multiple views of the same data at the same time.
● 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)
● SoC – Separation of Concerns: 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.
Routing is the process of monitoring the requests with the MVC application. In MVC,
the Application_Start() event registers all the routes in the routing table.
In ASP.NET MVC 5.0, a new type of routing is introduced, it is called Attribute Routing.
It enables the developers to define the routing using attributes on top of the controller
action method. To use the attribute routing in the MVC 5, you need to call the
MapMvcAttributeRoute method. The optional parameter for the URI can be added to the
route parameter using the question mark(?) in the attribute routing.
Example
A partial view is a chunk of HTML that can be safely inserted into an existing DOM.
Most commonly, partial views are used to componentize Razor views and make them
easier to build and update. Partial views can also be returned directly from controller
methods. In this case, the browser still receives text/HTML content but not necessarily
HTML content that makes up an entire page. As a result, if a URL that returns a partial
view is directly invoked from the address bar of a browser, an incomplete page may be
displayed. This may be something like a page that misses title, script and style sheets.
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 the complex data type.
Routing is the URL pattern that is mapped together to a handler and is responsible for
incoming browser request for a particular MVC controller. There are a total of three
segments for routing that are very significant in MVC
1. ControllerName
2. ActionMethodName
3. Parammeter
The filter in ASP.NET MVC is a class that is executed before or after an action method
is executed. It is a place where you can write custom logic that you want to execute. It
can be executed either to an action method or a controller. It is applied in two different
ways, declarative and programmatic. Applying the filter to the action or controller class
is called a declarative filter. Defining the interface for the filter is called the programmatic
way of applying a filter.
There are four types of built-in filters in ASP.NET MVC are authorization filter, action
filter, result filter, exception filter. These filters give an interface for which you can
define your custom filter.
An action filter is a type of filter in ASP.NET MVC that is executed to implement logic
before and after a controller is executed. These provide an additional attribute that is
applied to a section of the controller or the whole controller to modify it. These attributes
are defined under System.Attribute class.
● Output cache – It caches the output of a controller action. The output is cached here for
a defined amount of time.
● Handle Error – This filter is used to handle errors from the execution of controller action.
● Authorize – This filter is used to restrict access to the action method for a particular
user.
● Action Filters: Action filters are used to implement logic that gets executed before and
after a controller action executes. We will look at Action Filters in detail in this chapter.
● Authorization Filters: Authorization filters are used to implement authentication and
authorization for controller actions.
● Result Filters: Result filters contain logic that is executed before and after a view result
is executed. For example, you might want to modify a view result right before the view is
rendered to the browser.
● Exception Filters: Exception filters are the last type of filter to run. You can use an
exception filter to handle errors raised by either your controller actions or controller
action results. You can also use exception filters to log errors.
There is total of nine return types we can use to return results from a controller to view.
The base type of all these result types is ActionResult.
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 that
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 the 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.
Any web application has two main execution steps, first understanding the request and
depending on the type of the request sending out an 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.
● Multiple view support: Due to the separation of the model from the view, the user
interface can display multiple views of the same data at the same time.
● 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)
● SoC – Separation of Concerns: 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.
16) What does the MVC pattern define with 3 logical layers?
The Model is the part of the application, which only handles the logic for the application
data. Regularly, the model objects retrieve data (as well as store data) from a database.
The View is the part of the application, which takes care of the display of the data.
Most often, the views are created from the model data, although there are other, more
complicated methods of creating views.
The Controller, as the name implies, is the part of the application that handles user
interaction.
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 a call to the MapRoute() extension method
of RouteCollection.
In MVC HTML Helpers is a class which are used in views to render/display HTML
controls like links, TextBox, TextArea, etc.
This type of MVC routing uses attributes to define routes and gives developer more
control over the urls of web application.In order to use Attribute Routing first you have to
enable it by calling MapMvcAttributeRoutes during configuration.
routes.MapMvcAttributeRoutes();
}
}
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.
22) What are the Benefits of Area in MVC?
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.
A display mode is a powerful tool for all mobile-based apps development. However, it is
not limited to mobile web apps but it can also be used to display any alternative view,
which is tied to an existing controller. Display Modes practically give you another level of
flexibility on top of the default capabilities we saw in the last section. Display Modes can
also be used along with the previous feature so the users will simply build off of the site
they just created. It simplifies the ways to implement different versions of view for
different devices.
Route constraints in the ASP.NET are used to control the behavior of the route. With
route constraint, you can restrict your users to a set of URLs, or restrict browser
requests to match a particular route. The route constraints are defined by using a
regular expression. For eg: to set a constraint string to our hostname, we can use the
routing constraint as the following. Open the RouteConfig.cs file and modify the routing
entry as "abc/{controller}/{action}/{id}". Now the URL with string "abc" as the prefix will
only be able to access the site.
The Output cache in the ASP.NET MVC will increase the performance of your
application significantly. It is used to cache the value that is returned by the controller
action. So, when every time the controller action is invoked, the same value need not be
generated each time. To enable the output cache, use the OutputCache attribute to the
individual controller action or the entire controller class. You can also define the duration
for the content to be cached in the output cache.
Example:
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
[OutputCache(Duration=10, VaryByParam="none")]
public ActionResult Index()
{
return View();
}
}
}
In the above example, the output view is cached in the output cache for about 10
seconds.
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 extracts the whitespace and performs other types of compression to
make the downloaded files as small as possible. At runtime, the process recognizes the
agent of the user, for example, IE, Mozilla, etc. and then removes whatever is specific to
Mozilla when the request comes from IE.
The Validation Summary helper method generates an unordered list (UL element) of
validation messages that are in the Model State Dictionary object.
The Validation Summary 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
Validation Summary displays the error messages.
29) Explain what is Database First Approach in MVC using Entity Framework?
Database First Approach is an alternative or substitutes to the Code First and Model
First approaches to the Entity Data Model. The Entity Data Model creates model codes
(classes, properties, DbContext, etc.) from the database in the project and that class
behaves as the link between database and controller.
There are the following approaches, which are used to connect the database with the
application.
● Database First
● Model First
● Code First
GET Action Type: GET is used to request data from a specified resource. With all the
GET requests, we pass the URL, which is compulsory; however, it can take up the
following overloads.
POST Action Type: Tthe POST is used to submit data to be processed to a specified
resource. With all the POST requests, we pass the URL, which is essential and the
data. However, it can take up the following overloads.
31) What’s new in the latest version of MVC?
You can use Html.Raw helper to render raw Html in Asp.net MVC
Syntax