0% found this document useful (0 votes)
78 views

MVC Interview Questions

MVC is a software architectural pattern that separates an application into three main components: the model, the view, and the controller. The model manages the data, the view displays the data, and the controller handles user input. MVC provides separation of concerns and full control over HTML, CSS, and JavaScript.

Uploaded by

paparos486
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

MVC Interview Questions

MVC is a software architectural pattern that separates an application into three main components: the model, the view, and the controller. The model manages the data, the view displays the data, and the controller handles user input. MVC provides separation of concerns and full control over HTML, CSS, and JavaScript.

Uploaded by

paparos486
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

What is MVC (Model View Controller)?

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 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 MVC model defines web applications with 3 logic layers,

 The business layer (Model logic)


 The display layer (View logic)
 The input control (Controller logic)

MVC architecture represents the domain-specific data and business logic. It maintains the data of the
application, model data hold the data in public property.

We can also manipulate the data in the business logic layer

Namespace mvc.Models

   public class Student

   public int StudentId { get; set; }

   public string StudentName { get; set; }

   public int Age { get; set; }

In Model, we can apply validation to the property using Data Annotation instead of applying on the client
side. For adding data Annotation we need to add the reference
“System.ComponentModel.DataAnnotations assembly”

Like we apply on StudentId


Eg. 

[Display(Name=”StudentId ”)]

[Required(ErrorMessage=”StudentId is Required”)]

Public int StudenId {get;set;}

View : View is the User Interface where The user can display its own data and can modify its data, In
this, the data is passed from the model to the view. The view has a different folder with the same name as
of controller and has different views in it of different actions.

There are 3 types of Views in MVC

 User View : To create this view use page template. The inherited class name will be available in
<%@ page directive with inherits attributes.
 Master Page View : To create a master page view we use a template known as “MVC2 view
master page.it have a default extension of.master.
 Partial View : Partial View is the same as UserController in asp.net it is inherited from the
System.Web.Mvc

Controller: It is the most essential part of the MVC in asp.net since it is the first recipient which interacts
with HTTP and finds the model and actions. So it is the controller which decides which model should be
selected and how to carry the data from the respective view, a controller is inherited from the
System.Mvc.Controller. The routing map of the controller is decided in RouteConfig.cs which is under
App Start Folder.

Eg, http://localhost:61465/Employee/Mark

Where Employee is a controller name and mark is the action.

Learn more about ASP.NET MVC here: Overview Of ASP.NET MVC

Define Controller in MVC?

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):
Learn more here - ASP.Net MVC Controller

Explain Model in MVC?

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 Folde

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.

Learn more here - Model in ASP.Net MVC : Part 1

Explain View in MVC?

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


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).

Learn more here - ASP.Net MVC View

Explain in brief the role of different MVC components?

The different MVC components have the following roles -

 Presentation: This component takes care of the visual representation of a particular abstraction


in the application.

 Control: This component takes care of the consistency and uniformity between the abstraction
within the system along with their presentation to the user. It is also responsible for
communicating with all other controls within the MVC system.
 Abstraction: This component deals with the functionality of the business domain within the
application.

How will you maintain the sessions in MVC?

The sessions of an MVC can be maintained by 3 possible ways:

 viewdata

 temp data and

 view bag

Explain in brief the difference between adding routes in a webform application & an MVC
application?

We make use of the MapPageRoute() which is of the RouteCollection class for adding routes in a
webform application. Whereas, the MapRoute() method is used for adding routes to an MVC application.

How will you define the 3 logical layers of MVC?

The 3 logical layers of MVC can be defined as follows:

 Model logic which acts as a business layer

 View logic which acts as a display layer

 Controller logic acts as input control

What are the advantages of MVC?

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) 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.

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 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.

Here is a detailed article on Creating a Simple Application Using MVC 4.0.

What's new in MVC 6?

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.

Run on hosts other than IIS

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.

Environment based configuration system

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.

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.

Creating the request object,

The request object creation has four major steps. The following is a detailed explanation of the same.

Step 1 - Fill route

MVC requests are mapped to route tables which in turn specify which controller and action to be invoked.
So if the request is the first request the first thing is to fill the rout table with routes collection. This filling
of the route table happens the global.asax file

Step 2 - Fetch route

Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object
which has the details of which controller and action to invoke.

Step 3 - Request context created

The “RouteData” object is used to create the “RequestContext” object.

Step 4 - Controller instance created 

This request object is sent to “MvcHandler” instance to create the controller class instance. Once the
controller class object is created it calls the “Execute” method of the controller class.

Creating a Response object

This phase has two steps executing the action and finally sending the response as a result to the view.
Here is a complete article on ASP.Net MVC Life Cycle.

What is the concept of routing in MVC?

MVC routing can be defined as a pattern-matching scheme that is used for mapping incoming requests of
browsers to a definite MVC controller action.

What are the different properties of MVC routes?

MVC routes are accountable for governing which controller method will be executed for a given
URL. Thus, the URL comprises of the following properties:

 Route Name: It is the URL pattern which is used for mapping the handler.

 URL Pattern: It is another property containing the literal values as well as variable placeholders
(known as URL parameters).

 Defaults: This is the default parameter value assigned at the time of parameter creation.

 Constraints: These are used for applying against the URL pattern for more narrowly defining the
URL matching it.

What are the 3 important segments for routing?

The 3 important segments for routing are:

 ControllerName

 ActionMethodName

 Parameter
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  

public class HomeController: Controller

//URL: /Mvctest

[Route(“Mvctest”)]

public ActionResult Index()

ViewBag.Message = "Welcome to ASP.NET MVC!";

return View();

Attribute Routing with Optional Parameter  

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.   

public class HomeController : Controller

// Optional URI Parameter

// URL: /Mvctest/

// URL: /Mvctest/0023654

[Route(“Mvctest /{ customerName ?}”)]

public ActionResult OtherTest(string customerName){

ViewBag.Message = "Welcome to ASP.NET MVC!";

return View();
}

// Optional URI Parameter with default value

// URL: /Mvctest/

// URL: /Mvctest/0023654

[Route(“Mvctest /{ customerName =0036952}”)]

public ActionResult OtherTest(string customerName)

ViewBag.Message = "Welcome to ASP.NET MVC!";

return View();

Learn more here - Attribute Routing in ASP.Net MVC 5.0

How to execute any MVC project? Explain its steps.

For executing an MVC project, the steps followed are –

1. Receive the first request for the application

2. Then, the routing is performed

3. Then, the MVC request handler is created

4. After that, the controller is created and executed

5. Then, the action is invoked

6. Then, the results are executed

Mention & explain the different approaches you will use to implement Ajax in MVC?

There are 2 different approaches to implement Ajax in MVC. These are:

 jQuery: This is a library written using JavaScript for simplifying HTML-DOM manipulation.


 AJAX libraries: Asynchronous JavaScript and XML libraries are set of web development
libraries written using JavaScript and are used to perform common operations.

How will you differentiate between ActionResult and ViewResult?

Some common differentiation between ActionResult and ViewResult is –

ActionResult ViewResult
It becomes effective if you want to derive different types of It is not so effective in deriving
views dynamically different types of views dynamically
It is an abstract class, meaning it has methods and variables This has been derived from the
without the implementation body of instruction. ActionResult class
JsonResult, ViewResult, and FileStreamResult are some This class do not have its own derived
examples of its derived class class

Mention the significance of NonActionAttribute?

The various public methods that are associated with the controller class are considered to be the action
method. For preventing the default method, you have to allocate its public method with
NonActionAttribute.

Explain briefly the 2 approaches of adding constraints to an MVC route?

For adding constraints to an MVC route, the 2 different approaches are:

 By making use of regular expressions

 By making use of objects that implement the “IRouteConstraint” interface.

What "beforeFilter()","beforeRender" and "afterFilter" functions do in Controller?

 beforeFilter(): This function runs before every action in the controller. It's the right place to
check for an active session or inspect user permissions.

 beforeRender(): This function is called after controller action logic, but before the view is
rendered. This function is not often used but may be required if you are calling render() manually
before the end of a given action.

 afterFilter(): This function is called after every controller action and after rendering is done. It is
the last controller method to run.

What is the difference between MVVM and MVC?


Here are the important differences between MVVM and MVC:

MVC MVVM
A Controller is the entry point to the Application. The View is the entry point to the Application.
One to many relationships between View & View
One to many relationships between Controller & View.
Model.
View does not have reference to the Controller View have references to the View-Model.
MVC is Old Model MVVM is a relatively New Model.
The debugging process will be complicated when we
Difficult to read, change, to unit test, and reuse this Model
have complex data bindings.
Easy for separate unit testing and code is event-
MVC Model component can be tested separately from the user
driven.

What is the role of components Presentation, Abstraction, and Control in MVC?

Here is the role of components Presentation, Abstraction, and Control in MVC:

 Presentation: It is the visual representation of a specific abstraction within the application

 Abstraction: It is the business domain functionality within the application

 Control: It is a component that keeps consistency between the abstraction within the system and
their presentation to the user in addition to communicating with other controls within the system

Explain briefly what you understand by separation of concern.

Separation of Concerns can be defined as one of the core features as well as benefits of using MVC and is
supported by ASP.NET. Here, the MVC framework offers a distinct detachment of the different concerns
such as User Interface (UI), data and the business logic.

Explain RenderSection in MVC?

Answer

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.  

<div id="body">

@RenderSection("featured", required: false)


<section class="content-wrapper main-content clear-fix">

@RenderBody()

</section>

</div>

Learn more here - ASP.Net MVC 4 - Layout and Section in Razor

What is GET and POST Actions Types?

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.

.get(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ).done/.fail

POST

POST is used to submit data to be processed to a specified resource. With all the POST requests we pass
the URL which is compulsory and the data, however it can take the following overloads.

.post(url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

Learn more here - GET and POST Calls to Controller's Method in MVC

List out different return types of a controller action method?

There are total of nine return types we can use to return results from the controller to view.

The base type of all these result types is ActionResult.

ViewResult (View)

This return type is used to return a webpage from an action method.

PartialviewResult (Partialview)

This return type is used to send a part of a view 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.

RedirectToRouteResult (RedirectToAction, RedirectToRoute)


This return type is used when we want to redirect to any other action method.

ContentResult (Content)

This return type is used to return HTTP content type like text/plain as the result of the action.

jsonResult (json)

This return type is used when we want to return a JSON message.

javascriptResult (javascript)

This return type is used to return JavaScript code that will run in the browser.

FileResult (File)

This return type is used to send binary output in response.

EmptyResult

This return type is used to return nothing (void) in the result.

Here is a complete article on Various Return Types From MVC Controller.

What are the Filters in MVC?

In MVC, controllers define action methods and these action methods generally have a one-to-one
relationship with UI controls such as clicking a button or a link, etc. For example, in one of our previous
examples, the UserController class contained methods UserAdd, UserDelete, etc.

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

ASP.NET MVC framework supports the following action 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
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.
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.

Here is a complete article on Understanding Filters in MVC.

What are Action Filters in MVC?

Answer - Action Filters

Action Filters are additional attributes that can be applied to either a controller section or the entire
controller to modify the way in which action is executed. These attributes are special .NET classes
derived from System.Attribute which can be attached to classes, methods, properties, and fields.

ASP.NET MVC provides the following action filters,

 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

Specifies the return value to be cached for 10 seconds.

public class ActionFilterDemoController: Controller

[HttpGet]

OutputCache(Duration = 10)]

public string Index()

return DateTime.Now.ToString("T");

}
}

Learn more here: ASP.NET MVC with Action Filters

Explain what is routing in MVC? What are the three segments for routing important?

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 earlier days web
sites.

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 mapped together to a handler,routing 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

Code Example

ControllerName/ActionMethodName/{ParamerName} and also route map coding written in a


Global.asax file.

Learn more here - Routing in MVC.

What is Route in MVC? What is Default Route in MVC?

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.

Route definition Example of matching URL


{controller}/{action}/{id} /Products/show/beverages
{table}/Details.aspx /Products/Details.aspx
blog/{action}/{entry} /blog/show/123
{reporttype}/{year}/{month}/{day} /sales/2008/1/5
{locale}/{action} /US/show
{language}-{country}/{action} /en-US/show

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.

Mention what is the difference between Temp data, View, and View Bag?

In ASP.NET MVC there are three ways to pass/store data between the controllers and views.

ViewData

1. ViewData is used to pass data from controller to view.


2. It is derived from ViewDataDictionary class.
3. It is available for the current request only.
4. Requires typecasting for complex data types and checks for null values to avoid an error.
5. If redirection occurs, then its value becomes null.

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
1. TempData is derived from TempDataDictionary class
2. TempData is used to pass data from the current request to the next request
3. It keeps the information for the time of an HTTP Request. This means only from one page to
another. It helps to maintain the data when we move from one controller to another controller or
from one action to another action
4. It requires typecasting for complex data types and checks for null values to avoid an error.
Generally, it is used to store only one time messages like the error messages and validation
messages

Learn more here: Difference Between ViewData, ViewBag, and TempData

What is Partial View in MVC?

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,
Learn more here - Partial View in MVC

Explain what is the difference between View and Partial View?

View

 It contains the layout page.


 Before any view is rendered, viewstart page is rendered.
 A view might have markup tags like body, HTML, head, title, meta etc.
 The view is not lightweight as compare to Partial View.

Partial View

 It does not contain the layout page.


 Partial view does not verify for a viewstart.cshtml.We cannot put common code for a partial view
within the viewStart.cshtml.page.
 Partial view is designed specially to render within the view and just because of that it does not
consist any mark up.
 We can pass a regular view to the RenderPartial method.

Learn more here - Partial View in MVC

What are HTML helpers in MVC and its methods?

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.

In most cases, an HTML helper is just a method that returns a string. 

With MVC, you can create your own helpers, or use the built in HTML helpers.

Standard 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

<%=Html.ActionLink("About this Website", "About")%>

The first parameter is the link text, and the second parameter is the name of the controller action.

The Html.ActionLink() helper above, outputs the following HTML:

<a href="/Home/About">About this Website</a>

The Html.ActionLink() helper has several properties:

 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.

HTML Form Elements


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#

<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

<% using (Html.BeginForm()){%>

<p>

<label for="FirstName">First Name:</label>

<%= Html.TextBox("FirstName") %>

<%= Html.ValidationMessage("FirstName", "*") %>

</p>

<p>

<label for="LastName">Last Name:</label>

<%= Html.TextBox("LastName") %>

<%= Html.ValidationMessage("LastName", "*") %>

</p>

<p>

<label for="Password">Password:</label>

<%= Html.Password("Password") %>

<%= Html.ValidationMessage("Password", "*") %>

</p>

<p>
<label for="Password">Confirm Password:</label>

<%= Html.Password("ConfirmPassword") %>

<%= Html.ValidationMessage("ConfirmPassword", "*") %>

</p>

<p>

<label for="Profile">Profile:</label>

<%= Html.TextArea("Profile", new {cols=60, rows=10})%>

</p>

<p>

<%= Html.CheckBox("ReceiveNewsletter") %>

<label for="ReceiveNewsletter" style="display:inline">Receive Newsletter</label>

</p>

<p>

<input type="submit" value="Register" />

</p>

<%}%>

Learn more here - HTML Helpers in MVC: Part 1

 Standard HtmlHelper methods

Some of the standard helper methods are,

 ActionLink: Renders an anchor.


 BeginForm: Renders HTML form tag
 CheckBox: Renders check box.
 DropDownList: Renders drop-down list.
 Hidden: Renders hidden field
 ListBox: Renders list box.
 Password: Renders TextBox for password input
 RadioButton: Renders radio button.
 TextArea: Renders text area.
 TextBox: Renders text box.

Learn more here - HtmlHelper Methods in ASP.NET MVC


Explain attribute based routing in MVC? 

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".

Hide Copy Code

public class HomeController: Controller

[Route("Users/about")]

publicActionResultGotoAbout()

return View();

Learn more here - Attribute Based Routing in ASP.Net MVC 5

What is TempData in MVC?

TempData is a dictionary object to store data temporarily. It is a TempDataDictionary class type and
instance property of the Controller base class.

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.

TempDataDictionary is inherited from the IDictionary<string, object>, ICollection<KeyValuePair<string,


object>>, IEnumerable<KeyValuePair<string, object>> and IEnumerable interfaces.

Example   

public ActionResult FirstRequest()

List < string > TempDataTest = new List < string > ();

TempDataTest.Add("Tejas");
TempDataTest.Add("Jignesh");

TempDataTest.Add("Rakesh");

TempData["EmpName"] = TempDataTest;

return View();

public ActionResult ConsecutiveRequest()

List < string > modelData = TempData["EmpName"] as List < string > ;

TempData.Keep();

return View(modelData);

Learn more here - All About the TempData in MVC

What is Razor in MVC?

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.

MVC 3 has introduced a new view engine called Razor.

Why is Razor?

1. Compact & Expressive.


2. Razor minimizes the number of characters and keystrokes required in a file, and enables a fast
coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to
explicitly denote server blocks within your HTML. The parser is smart enough to infer this from
your code. This enables a really compact and expressive syntax which is clean, fast and fun to
type.
3. Easy to Learn: Razor is easy to learn and enables you to quickly be productive with a minimum
of effort. We can use all your existing language and HTML skills.
4. Works with any Text Editor: Razor doesn't require a specific tool and enables you to be
productive in any plain old text editor (notepad works great).
5. Has great Intellisense:
6. Unit Testable: The new view engine implementation will support the ability to unit test views
(without requiring a controller or web-server, and can be hosted in any unit test project - no
special app-domain required).

Learn more here - Brief Introduction to MVC3


Differences between Razor and ASPX View Engine in MVC?

Learn more here - ASPX View Engine VS Razor View Engine

What are the Main Razor Syntax Rules?

Answer

 Razor code blocks are enclosed in @{ ... }


 Inline expressions (variables and functions) start with @
 Code statements end with semicolon
 Variables are declared with the var keyword
 Strings are enclosed with quotation marks
 C# code is case sensitive
 C# files have the extension .cshtml

C# Example

<!-- Single statement block -->

@{

varmyMessage = "Hello World";

<!-- Inline expression or variable -->

< p > The value of myMessage is: @myMessage < /p>

<!-- Multi-statement block -->

@{

var greeting = "Welcome to our site!";

varweekDay = DateTime.Now.DayOfWeek;

vargreetingMessage = greeting + " Here in Huston it is: " + weekDay;

} < p > The greeting is: @greetingMessage < /p>

Learn more here - Introduction to Microsoft ASP.NET MVC 3 Razor View Engine

How do you implement Forms authentication in MVC?

Answer

Authentication is giving access to the user for a specific service by verifying his/her identity using his/her
credentials like username and password or email and password. It assures that the correct user is
authenticated or logged in for a specific service and the right service has been provided to the specific
user based on their role that is nothing but authorization.

ASP.NET forms authentication occurs after IIS authentication is completed. You can configure forms
authentication by using forms element with in web.config file of your application. The default attribute
values for forms authentication are shown below,  

<system.web>

<authenticationmode="Forms">

<formsloginUrl="Login.aspx" protection="All" timeout="30" name=".ASPXAUTH" path="/"


requireSSL="false" slidingExpiration="true" defaultUrl="default.aspx" cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" />

</authentication>

</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.

Learn more here - Form Authentication in MVC 5: Part 1

Explain Areas in MVC?

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();

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.

Learn more here - What Are Areas in ASP.Net MVC - Part 6

Explain the need of display mode in MVC?

Answer

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.

Using display modes involves in 2 steps

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.

Learn more here - Display Mode Provider in MVC 5 Application

Explain the concept of MVC Scaffolding?

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.

Learn more here - Terminologies in MVC: Part 3 (Scaffolding)

What is Route Constraints in MVC?

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.

Add constraint to URL

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:

Learn more here - Route Constraints in MVC

What is Razor View Engine in MVC?

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.

Learn more here - Getting Started with Razor View Engine in MVC 3

What is Output Caching in MVC?

Answer
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.

Keep the following in mind,

 Avoid caching contents that are unique per user.


 Avoid caching contents that are accessed rarely.
 Use caching for contents that are accessed frequently.

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.

Cached Content Locations

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".

Learn more here - Output Caching in MVC

What is Bundling and Minification in MVC?

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.

Learn more here - Bundling and Minification in Visual Studio 2012 or Migrate Existing Website

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

MvcHtmlStringValidateMessage(bool excludePropertyErrors, string message, object htmlAttributes)

Display field level error messages using ValidationSummary


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

@Html.ValidationSummary(false, "", new { @class = "text-danger" })

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.

Learn more here - Understanding Validation In MVC - Part 4

What is Database First Approach in MVC using Entity Framework?

Answer

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.

Learn more here - Database First Approach With ASP.NET MVC Step By Step Part 1

What are the Folders in MVC application solutions?

Answer - Understanding the folders

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.

What is difference between MVC and Web Forms?

Answer - ASP.Net MVC / Web Forms difference

The following are some difference.


ASP.Net MVC ASP.Net Web Forms
View and logic are separate, it has separation of concerns No separation of concerns; Views are tightly coupled with
theory. MVC 3 onwards has .aspx page as .cshtml. logic (.aspx.cs /.vb file).
Introduced concept of routing for route based URL.
File-based routing .Redirection is based on pages.
Routing is declared in Global.asax for example.
Support Razor syntax as well as .aspx Support web forms syntax only.
State management handled via Tempdata, ViewBag, and
View Data. Since the controller and view are not State management handled via View State. Large viewstate,
dependent and also since there is no view state concept in in other words increase in page size.
ASP.NET, MVC keeps the pages lightweight.
Partial Views User Controls
HTML Helpers Server Controls
Multiple pages can have the same controller to satisfy Each page has its own code, in other words direct
their requirements. A controller may have multiple dependency on code. For example Sachin.aspx is dependent
Actions (method name inside the controller class). on Sachin.aspx.cs (code behind) file.
Unit Testing is quite easier than ASP.Net Web forms
Direct dependency, tight coupling raises issues in testing.
Since a web form and code are separate files.
Layouts Master pages

Here are more Similarities and Dissimilarities Between MVC and Web Forms.

What are the methods of handling an Error in MVC?

Answer

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.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)

filters.Add(new HandleErrorAttribute());

protected void Application_Start()

AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

Important properties of HandleError attribute

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.

Master

Master View for displaying the exception.

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  

[HandleError(View = "Error")]

public class HomeController: Controller

public ActionResult Index()

ViewBag.Message = "Welcome to ASP.NET MVC!";

int u = Convert.ToInt32(""); // Error line

return View();

}
HandleError Attribute at Action Method Level, 

[HandleError(View = "Error")]

public ActionResult Index()

ViewBag.Message = "Welcome to ASP.NET MVC!";

int u = Convert.ToInt32(""); // Error line

return View();

Here are more details on Exception or Error Handling in ASP.Net MVC Using HandleError Attribute.

What is ViewStart?

Answer

Razor View Engine introduced a new layout named _ViewStart which is applied on all view
automatically. Razor View Engine firstly executes the _ViewStart and then start rendering the other view
and merges them.

Example of Viewstart

@{

Layout = "~/Views/Shared/_v1.cshtml";

< !DOCTYPE html >

< html >

< head >

< meta name = "viewport"

content = "width=device-width" / >

< title > ViewStart < /title> < /head> < body >

< /body>

< /html>
Learn more here - Viewstart Page in ASP.NET MVC 3

What is JsonResultType in MVC?

Answer

Action methods on controllers return JsonResult (JavaScript Object Notation result) that can be used in an
AJAX application. This class is inherited from the "ActionResult" abstract class. Here Json is provided
one argument which must be serializable. The JSON result object that serializes the specified object to
JSON format.

public JsonResult JsonResultTest()

return Json("Hello My Friend!");

Learn more here - ActionResult Return Type in MVC 3.0

What is TempData?

Answer - Tempdata

 TempData is a dictionary object derived from the TempDataDictionary class.


 TempData is used to pass data from the current request to a subsequent request, in other words in
the case of redirection.
 The life of a TempData is very short and it retains its value for a short period of time.
 It requires typecasting for complex data type as I’ve used in my example:
 @foreach (var item in
(List<MVCSample.Models.EmpRegistration>)TempData["EmployeeRegistration"])
 You can retain its value using the Keep method for subsequent requests.

How to use ViewBag?


Answer

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.

public ActionResult StudentSummary()

var student = new Student()

Name = "Sandeep Singh Shekhawat",

Age = 24,

City = "Jaipur"

};

ViewBag.Student = student;

return View();

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.

@{

ViewBag.Title = "Student Summary";

var student = ViewBag.Student;

< table >

< tr >

< th > Name < /th> < th > Age < /th> < th > City < /th> < /tr> < tr >

< td > @student.Name < /td> < td > @student.Age < /td> < td > @student.City < /td> < /tr>

< /table>
Here we used one more thing, "ViewBag.Title", that shows the title of the page. 

Learn more here - Displaying Data on View From Controller

What are the Difference between ViewBag&ViewData?

Answer - Difference between ViewBag&ViewData?

 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";

Learn more here - Difference Between ViewBag & ViewData in MVC

What is Data Annotation Validator Attributes in MVC?

Answer - Using the Data Annotation Validator Attributes

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.

Some of the DataAnnotation used for validation are given below,


1. Required
Specify a property as required.
[Required(ErrorMessage="CustomerName is mandatory")]
2. RegularExpression
Specifies the regular expression to validate the value of the property.
[RegularExpression("[a-z]", ErrorMessage = "Invalid character")]
3. Range
Specifies the Range of values between which the property values are checked.
[Range(1000,10000,ErrorMessage="Range should be between 1k & 10k")]
4. StringLength
Specifies the Min & Max length for a string property.
[StringLength(50, MinimumLength = 5, ErrorMessage = "Minimum char is 5 and maximum char
is 10")]
5. MaxLength
Specifies the Max length for the property value.
[MaxLength(10,ErrorMessage="Customer Code is exceeding")]
6. MinLength
It is used to check for minimum length.
[MinLength(5, ErrorMessage = "Customer Code is too small")]

Learn more here - Adding Custom Validation in MVC

How can we done Custom Error Page in MVC?

Answer

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.

<system.web>

<customErrors mode="On">

</system.web>

Then, your action method needs to be marked with the atttribute.

[HandleError]

public class HomeController: Controller

[HandleError]

publicActionResultThrowException()

throw new ApplicationException();


}

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.   

[HandleError]

public class HomeController: Controller

[HandleError(View = "CustomErrorView")]

publicActionResultThrowException()

{
throw new ApplicationException();

Learn more here - Custom Error Page in ASP.NET MVC

Server Side Validation in MVC?

Answer

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.

Approach 1 - Manually Add Error to ModelState object

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,

namespace ServerValidation.Models

public class User

public string Name

get;

set;

public string Email

get;

set;
}

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. 

using System.Text.RegularExpressions;

using System.Web.Mvc;

namespace ServerValidation.Controllers

public class UserController: Controller

public ActionResult Index()

return View();

[HttpPost]

public ActionResult Index(ServerValidation.Models.User model)

if (string.IsNullOrEmpty(model.Name))

ModelState.AddModelError("Name", "Name is required");

if (!string.IsNullOrEmpty(model.Email))

{
string emailRegex = @ "^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +

@ "\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +

@ ".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

Regex re = new Regex(emailRegex);

if (!re.IsMatch(model.Email))

ModelState.AddModelError("Email", "Email is not valid");

} else {

ModelState.AddModelError("Email", "Email is required");

if (ModelState.IsValid)

ViewBag.Name = model.Name;

ViewBag.Email = model.Email;

return View(model);

Thereafter I create a view (Index.cshtml) for the user input under the User folder.

@model ServerValidation.Models.User

@{

ViewBag.Title = "Index";

@using(Html.BeginForm())
{

if (@ViewData.ModelState.IsValid)

if (@ViewBag.Name != null)

{<b>

Name: @ViewBag.Name < br / >

Email: @ViewBag.Email < /b>

} < fieldset >

< legend > User < /legend> < div class = "editor-label" >

@Html.LabelFor(model => model.Name) < /div> < div class = "editor-field" >

@Html.EditorFor(model => model.Name)

@if(!ViewData.ModelState.IsValid)

< span class = "field-validation-error" > @ViewData.ModelState["Name"].Errors[0].ErrorMessage <


/span>

< /div> < div class = "editor-label" >

@Html.LabelFor(model => model.Email) < /div> < div class = "editor-field" >

@Html.EditorFor(model => model.Email)

@if(!ViewData.ModelState.IsValid)

< span class = "field-validation-error" > @ViewData.ModelState["Email"].Errors[0].ErrorMessage <


/span>

< /div> < p >


< input type = "submit"

value = "Create" / >

< /p> < /fieldset>

What is the use of remote validation in MVC?

Answer

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:  

public class UserModel

[Required]

public string UserName

get;

set;

[Remote("CheckExistingEmail", "Home", ErrorMessage = "Email already exists!")]

public string UserEmailAddress

get;

set;

}
Let's get some understanding of the remote attribute used, so the very first parameter
“CheckExistingEmail” is the the name of the action. The second parameter “Home” is referred to as
controller so to validate the input for the UserEmailAddress the “CheckExistingEmail” action of the
“Home” controller is called and the third parameter is the error message. Let's implement the
“CheckExistingEmail” action result in our home controller.

public ActionResult CheckExistingEmail(string UserEmailAddress)  
{  
    bool ifEmailExist = false;  
    try  
    {  
        ifEmailExist = UserEmailAddress.Equals("[email protected]") ? true : false;  
        return Json(!ifEmailExist, JsonRequestBehavior.AllowGet);  
    } catch (Exception ex)  
    {  
        return Json(false, JsonRequestBehavior.AllowGet);  
    }  
}

Learn more here - Remote Validation in MVC

What are the Exception filters in MVC?

Answer

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.

Let's start!

A Yellow screen of Death can be said is as a wardrobe malfunction of our application.

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.

Creating an Exception Filter

Custom Exception Filters must implement the builtinIExceptionFilter interface. The interface looks as in
the following,

public interface IExceptionFilter

{
void OnException(ExceptionContext filterContext)

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:  

Name Type Detail


Result ActionResult The result returned by the action being invoked.
Exception Exception The unhandled exceptions caused from the actions in the applications.
This is a very handy property that returns a bool value (true/false) based
ExceptionHandled BOOL on if the exception is handled by any of the filters in the applicaiton or
not.

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.

public class CustomExceptionFilter: FilterAttribute, IExceptionFilter

public void OnException(ExceptionContext filterContext)

if (!filterContext.ExceptionHandled && filterContext.Exception is NullReferenceException)

filterContext.Result = new RedirectResult("customErrorPage.html");

filterContext.ExceptionHandled = true;

Learn more here - Exception Filters in MVC

Name the assembly in which the MVC framework is typically defined.


In the System.Web.Mvc, the MVC framework is usually defined.

How do you implement Forms authentication in MVC?

Authentication is to give access to the user for a specific service by verifying his/her identity using his/her
credentials like username and password. 

After IIS authentication, ASP.NET form authentication occurs. We can configure forms authentication by
using forms element in web.config. The default attribute values for forms authentication are shown
below,

<system.web>  

    <authenticationmode="Forms">  

        <formsloginUrl="Login.aspx" protection="All" timeout="30" name=".ASPXAUTH" path="/"


requireSSL="false" slidingExpiration="true" defaultUrl="default.aspx" cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" />  

        </authentication>  

</system.web>  

The FormsAuthentication class creates the authentication cookie automatically when SetAuthCookie() or
RedirectFromLoginPage() methods are called. The value of an authentication cookie contains a string
representation of the encrypted and signed FormsAuthenticationTicket object.

What is the difference between Html.Partial and Html.RenderPartial?

Html.RenderPartial is directly written to the HTTP response stream which is used the same Text Writer
object as used in the current webpage/template. Since there is no return type of Validation Annotations in
MVC, the return type of Validation Annotations is void. We don't need to create any actions so it is
simple to use, it is very useful when we want to show the data which is in another model view.

For example: if we want to show comments of an article, we will prefer to use RenderPartial method
since the information and comments of the article are already populated in the view model.

@{Html.RenderPartial("_Comments");}

When it is executed its result is directly written to the response stream which makes it faster when
compared with the partial method

In Html.Partial, the partial view is viewed as an encoded HTML string. Due to its string value return type,
we can store the Html.Partial value in a variable.it same as Html.RenderPartial in case of action creation
also,  we don’t need to create action, Partial method is also useful when the displaying data in the partial
view is already in the corresponding view model which same as html.RenderPartial.

@Html.Partial("_Comments")
What was the need to introduce WebAPI technology?

Answer: HTTP was earlier used as a protocol for all types of clients. But with time, the client variety
started increasing and spreading out in different directions.  The use of JavaScript, Windows applications,
and even mobile demanded the high consumption of HTTP. Due to this reason, the REST approach was
proposed. WebAPI technology, therefore, applied the REST principles to expose the data over HTTP.

Do you know about Glimpse?

Yes, Glimpse helps in finding out the performance, supports debugging, and also helps in diagnosing
information. It helps in gaining information about the routes, timelines, model binding, etc.

What can help in navigating from one view to another using a hyperlink?

Answer: The Action link can help in navigating from one view to another using the hyperlink, which
creates a simple URL and navigates to the “Home” controller and also generates the Gotohome action.

Which filters can you execute at the end?

Answer: In the end, we can apply filters, namely “Exceptional Filters.”

What is the use of Keep and Peek in “TempData”?

Once “TempData” is read in the current request, it’s not available in the subsequent request. If we want
“TempData” to be read and also available in the subsequent request then after reading we need to call
“Keep” method as shown in the code below.

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.

1 string str = TempData.Peek("Td").ToString();

What is WebAPI?

HTTP is the most used protocol. Since many years, the browser was the most preferred client by which
we consumed data exposed over HTTP. But as years passed by, client variety started spreading out. We
had demanded to consume data on HTTP from clients like mobile, JavaScript, Windows applications, etc.

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.

What is Code Blocks in Views?


Unlike code expressions that are evaluated and sent to the response, it is the blocks of code that are
executed. This is useful for declaring variables which we may be required to be used later.

1 @{
2 int x = 123;
3 string y = “aa”;
4 }

[ASP.NET MVC 5] You have a page with Razor C# syntax. What is the difference between these
two methods, RenderAction and RenderPartial? What will they do?

@{

Html.RenderAction("Add");

Html.RenderPartial("Add");

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.

What is the difference between asynchronous and synchronous actions? When would you use
asynchronous actions?

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.

You have an ASP.NET MVC application where you need to use ASP.NET session state and support
running across several servers. What additional configuration can you perform without writing
custom code?

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.

What is the recommended approach for ASP.NET MVC to globally intercept exceptions? What
other functionality can be implemented with the approach?

You can create a custom exception filter to intercept and log unhandled exceptions.

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.
You have a controller CategoriesController with actions ShowAll, Add, and Delete. You’ve got
several requirements related to application URLs:

URL Action Method

~/v2/Categories ShowAll GET

~/v2/Categories/Add Add POST

DELET
~/v2/Categories/Delete Delete E

What is the easiest way to achieve that?

Hide answer

In ASP.NET MVC 5:

Use a custom route and attributes on action methods to restrict HTTP methods.

Step 1: We need to add a custom route to RoutesCollection (usually


in ~/App_Start/RoutesConfig) before the default one:

routes.MapRoute(

name: "v2",

url: "v2/{controller}/{action}",

defaults: new { action = "ShowAll" }

);

Step 2: To restrict HTTP methods for actions, we need to mark CategoriesController’s methods with the
attributes [HttpGet], [HttpPost], and [HttpDelete] according to our requirements.

In ASP.NET Core MVC:

There are three ways to fulfill these requirements.

Option #1: Add a custom global route and attributes on action methods to restrict HTTP methods.

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}"

);

Step 2: To restrict HTTP methods for actions, we need to mark CategoriesController’s methods with the
attributes [HttpGet], [HttpPost], and [HttpDelete] according to our requirements.

This is a good approach for applications without specific requirements for a URL scheme.

Option #2: Configure routes at the action level.

Steps:

1. Mark actions with attributes to restrict allowed HTTP methods.

2. Specify route templates via attributes:

[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:
1. Specify a basic controller route template with an attribute.

2. Mark actions with attributes to restrict allowed HTTP methods.

3. Specify relative route templates via attributes:

[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.

What basic folders do we have in an ASP.NET project without Areas? What are they for? What
subfolders do they have (if applicable)? Which folders are publicly accessible?

Hide answer

 App_Data can be used to store some application’s data.

 App_Start contains configuration classes: RouteConfig, BundleConfig, etc.


 Content is a publicly accessible folder for static files, such as CSS files, images, etc., but not
scripts.

 Controllers is a default folder for application controllers.

 Scripts is a publicly accessible folder for JavaScript files.

 Views: The folder contains a folder for every controller, plus a special folder Shared for views
used by multiple views/controllers. For example, if we have a controller called HomeController,
we will have a Home subfolder here with all the views related to HomeController.

You might also like