ASP.NET MVC Interview Questions & Answers
Click if you like the project. Pull Request are highly appreciated. Follow me @kansiris87 for technical updates.
Table of Contents
| No. | Questions |
|---|---|
| 1 | What is MVC? |
| 2 | Explain MVC design pattern? |
| 3 | What is Domain Driven Design and Development? |
| 4 | What is MVP pattern? |
| 5 | What is MVVM pattern? |
| 6 | What is ASP.NET MVC? |
| 7 | How MVC pattern works in ASP.NET MVC? |
| 8 | How Model, View and Controller communicate with each other in ASP.NET MVC? |
| 9 | What are advantages of ASP.NET MVC? |
| 10 | Explain brief history of ASP.NET MVC? |
| 11 | What is difference between 3-layer architecture and MVC architecture? |
| 12 | What is difference between ASP.NET WebForm and ASP.NET MVC? |
| 13 | What is ViewModel in ASP.NET MVC? |
| 14 | Explain ASP.NET MVC pipeline? |
| 15 | What is Routing in ASP.NET MVC? |
| 16 | How to define a route in ASP.NET MVC? |
| 17 | What is Attribute Routing and how to define it? |
| 18 | When to use Attribute Routing? |
| 19 | How to enable Attribute Routing in ASP.NET MVC? |
| 20 | How to define Attribute Routing for Area in ASP.NET MVC? |
| 21 | What is difference between Routing and URL Rewriting? |
| 22 | What is Route Constraints in ASP.NET MVC? |
| 23 | How route table is created in ASP.NET MVC? |
| 24 | What are important namespaces in ASP.NET MVC? |
| 25 | What is View Engine? |
| 26 | How View Engine works? |
| 27 | What is Razor View Engine? |
| 28 | How to make Custom View Engine? |
| 29 | How to register Custom View Engine in ASP.NET MVC? |
| 30 | Can you remove default View Engine in ASP.NET MVC? |
| 31 | What is difference between Razor and WebForm engine? |
| 32 | What are HTML Helpers in ASP.NET MVC? |
| 33 | What are different types of HTML Helpers? |
| 34 | What are Url Helpers? |
| 35 | What is Validation Summary? |
| 36 | What are AJAX Helpers? |
| 37 | What is unobtrusive AJAX? |
| 38 | What are various configuration options for AJAX Helpers? |
| 39 | What is Cross Domain AJAX? |
| 40 | What are Layouts in ASP.NET MVC? |
| 41 | What are Sections in ASP.NET MVC? |
| 42 | What are RenderBody and RenderPage in ASP.NET MVC? |
| 43 | What are Styles.Render and Scripts.Render? |
| 44 | How to enable and disable optimizations in ASP.NET MVC? |
| 45 | What is ViewStart? |
| 46 | When to use _ViewStart? |
| 47 | What are different ways of rendering layout in ASP.NET MVC? |
| 48 | What is App_Start folder in ASP.NET MVC? |
| 49 | What are different ways of returning/rendering a view in ASP.NET MVC? |
| 50 | What are differences among ViewData, ViewBag, TempData and Session? |
| 51 | How to persist data in TempData? |
| 52 | How to control Session behavior in ASP.NET MVC? |
| 53 | How TempData is related to Session in ASP.NET MVC? |
| 54 | What are Action methods in ASP.NET MVC? |
| 55 | What is ActionResult and how is it different from others? |
| 56 | How to make a Non-Action method in ASP.NET MVC? |
| 57 | Can you change action method name? |
| 58 | How to restrict an action method to be invoked only by HTTP GET, POST, PUT or DELETE? |
| 59 | How to determine an action method is invoked by HTTP GET or POST? |
| 60 | How to determine an AJAX request? |
| 61 | What is Data Annotations in ASP.NET MVC? |
| 62 | How to apply Server side validation in ASP.NET MVC? |
| 63 | How to determine there is no error in Model State? |
| 64 | How to enable and disable client-side validation in ASP.NET MVC? |
| 65 | What is a CDN and advantages of CDN? |
| 66 | What is jquery.validate.unobtrusive.js? |
| 67 | What is Bundling and Minification in ASP.NET MVC? |
| 68 | Can we use Bundling and Minification in ASP.NET MVC3 or ASP.NET4.0? |
| 69 | How Bundling use browser Cache capability? |
| 70 | What is Partial View in ASP.NET MVC? |
| 71 | How do you return a partial view from controller? |
| 72 | What are different ways of rendering a Partial View in ASP.NET MVC? |
| 73 | What is Area in ASP.NET MVC? |
| 74 | How to register Area in ASP.NET MVC? |
| 75 | What is Child action and how to invoke it? |
| 76 | What is Scaffolding? |
| 77 | How Scaffold templates works in ASP.NET MVC? |
| 78 | What are ASP.NET MVC Filters and Attributes? |
| 79 | What are different types of Filters in ASP.NET MVC? |
| 80 | When Exception filters are executed in ASP.NET MVC? |
| 81 | What is the order of execution of filters in ASP.NET MVC? |
| 82 | How to configure filters in ASP.NET MVC? |
| 83 | How Authentication and Authorization work in ASP.NET MVC? |
| 84 | How Forms Authentication and Authorization work in ASP.NET MVC? |
| 85 | How to implement custom Forms Authentication and Authorization in MVC? |
| 86 | How to allow HTML tags in ASP.NET MVC? |
| 87 | What is caching and when to use it? |
| 88 | What are advantages of caching? |
| 89 | What is output caching? |
| 90 | What is Donut caching and Donut hole caching in ASP.NET MVC? |
| 91 | What is loose coupling and how is it possible? |
| 92 | What are Dependency Inversion Principle (DIP) and IoC? |
| 93 | What is Dependency Injection (DI)? |
| 94 | What is Service Locator? |
| 95 | What are different ways to implement Dependency Injection (DI)? |
| 96 | What are advantages of Dependency Injection (DI)? |
| 97 | What is IoC or DI container? |
| 98 | What are popular DI containers? |
| 99 | What is Test Driven Development (TDD)? |
| 100 | What are commonly used tool for Unit Testing in ASP.NET MVC? |
ASP.NET MVC
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.
The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating web applications. The ASP.NET MVC Framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentications. The MVC framework is defined in the System.Web.Mvc assembly. It provides full control over HTML, JavaScript and CSS. It\’s the better as well as a recommended approach for large-scale applications where various teams are working together.
MVC is a framework for building web applications using a MVC (Model View Controller) design:
• The Model represents the application core (for instance a list of database records).
• The View displays the data (the database records).
• The Controller handles the input (to the database records).
The MVC model also provides full control over HTML, CSS, and JavaScript.
The MVC model defines web applications with 3 logic layers:
• The business layer (Model logic)
• The display layer (View logic)
• The input control (Controller logic)
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.
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 a type 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 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.
Full features of ASP.NET – One of the key advantages of using ASP.NET MVC is that it is built on top of ASP.NET framework and hence most of the features of the ASP.NET like membership providers, roles, etc can still be used.
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 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 the detailed explanation of the same(short cut to remember FFRCAR)
Step 1: Fill route
MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.
Step 2: Fetch route
Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.
Step 3: Request context created
The “RouteData” object is used to create the “RequestContext” object.
Step 4: Controller instance created
This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.
Creating Response object: This phase has two steps executing the action and finally sending the response as a result to the view.
List out different return types of a controller action method?
Controller actions are methods defined in the controller class and responsible to perform required operations on the user\’s inputs like as form values, query strings values etc. with the help of Model and passing the results back to the View. There are total nine return types we can use to return results from 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.Returns a ViewResult which renders the specified or default view by using controller View() helper method
PartialviewResult (Partialview): This return type is used to send a part of a view which will be rendered in another view. or Returns a PartialViewResult which renders the specified or default partial view (means a view without its layout) by using controller PartialView() helper method.
RedirectResult (Redirect): This return type is used to redirect to any other controller and action method depending on the URL.or. Returns a RedirectResult which Issues an HTTP 301 or 302 redirection to a specific URL by using controller Redirect() helper method.
RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is used when we want to redirect to any other action method. or. Returns a RedirectToRouteResult which Issues an HTTP 301 or 302 redirection to an action method or specific route entry by using controller RedirectToAction(), RedirectToActionPermanent(), RedirectToRoute(), RedirectToRoutePermanent() helper methods.
ContentResult (Content): This return type is used to return HTTP content type like text/plain as the result of the action. or . Returns a ContentResult which renders raw text like as \”Hello, DotNet Tricks!\” by using controller Content() helper method.
jsonResult (json): This return type is used when we want to return a JSON message. or. Returns a JsonResult which serializes an object in JSON format ( like as \”{ \”Message\”: Hello, World! }\”) and renders it by using controller Json() helper method.
javascriptResult (javascript): This return type is used to return JavaScript code that will run in browser. or. Returns a JavaScriptResult which renders a snippet of JavaScript code like as \”function hello() { alert(Hello, World!); }\” by using controller JavaScript() helper method. This is used only in AJAX scenarios.
FileResult (File): This return type is used to send binary output in response. or.Returns a FileResult which renders the contents of a file like as PDF, DOC, Excel etc. by using controller File() helper method.
EmptyResult: This return type is used to return nothing (void) in the result. or. Returns no result returned by an action. This has no controller helper method.
HttpNotFoundResult – Returns an HttpNotFoundResult which renders a 404 HTTP Status Code response by using controller HttpNotFound() helper method.
HttpUnauthorizedResult – Returns an HttpUnauthorizedResult which renders a 401 HTTP Status Code (means \”not authorized\”) response. This has no controller helper method. This is used for authentication (forms authentication or Windows authentication) to ask the user to log in.
HttpStatusCodeResult – Returns an HttpStatusCodeResult which renders a specified HTTP code response. This has no controller helper method.
What are 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 feature to add pre and post action behaviors on 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 most commonly used filters to perform additional data processing, or manipulating the return values or cancelling the execution of action or modifying the view structure at run time.
What are Action Filters in MVC?
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:
E.g.: Specifies the return value to be cached for 10 seconds.
publicclassActionFilterDemoController: Controller
{ [HttpGet]
OutputCache(Duration = 10)]
publicstringIndex()
{ returnDateTime.Now.ToString(\”T\”); } }
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 give desired response. In this case, URL is not mapped to specific files or folder as was the case of earlier day’s web sites.
There are two types of routing (after the introduction of ASP.NET MVC 5).
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.
Attribute based routing: to define this type of routing, we specify the Route attribute in the action method of the controller.
Routing is the URL pattern that is mappped together to a handler,rounting is responsible for incoming browser request for particular MVC controller. In other ways let us say routing help you to define a URL structure and map the URL with controller. There are three segments for routing that are important,
-
ControllerName
-
ActionMethodName
-
Parammeter
i.e: ControllerName/ActionMethodName/{ParamerName} and also route map coding written in a Global.asax file.
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 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.
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 call to the MapRoute() extension method of RouteCollection.
Mention what is the difference between Temp data, View, Session and View Bag?
Or
How can we pass the data From Controller to View in MVC?
In ASP.NET MVC there are three ways to pass/store data between the controllers and views.
ViewData:
ViewData is used to pass data from controller to view.
It is derived from ViewDataDictionary class.
It is available for the current request only.
Requires typecasting for complex data type and checks for null values to avoid error.
If redirection occurs, then its value becomes null.
ViewBag:
ViewBag is also used to pass data from the controller to the respective view.
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
It is also available for the current request only.
If redirection occurs, then its value becomes null.
Doesn’t require typecasting for complex data type.
TempData:
TempData is derived from TempDataDictionary class
TempData is used to pass data from the current request to the next request
It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when
we move from one controller to another controller or from one action to another action
It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages.
Session
Session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it never expires.
Session is valid for all requests, not for a single redirect.
It’s also required typecasting for getting data and check for null values to avoid error.
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 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 other view. For example, let’s say all the pages of your site have a standard structure with left menu, header, and footer as in the following image,
Explain what is the difference between View and Partial View?
View:
• It contains the layout page.
• Before any view is rendered, viewstart page is rendered.
• View might have markup tags like body, html, head, title, meta etc.
• View is not lightweight as compare to Partial View.
Partial View:
It does not contain the layout page.
Partial view does not verify for a viewstart.cshtml.We cannot put common code for a partial view within the viewStart.cshtml.page.
Partial view is designed specially to render within the view and just because of that it does not consist any mark up.
We can pass a regular view to the RenderPartial method.
What are HTML Helpers in ASP.NET MVC?
An HTML Helper is just a method that returns a HTML string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML , and tags etc.
You can also create your own HTML Helpers to render more complex content such as a menu strip or an HTML table for displaying database data.
What are different types of HTML Helpers?
There are three types of HTML helpers as given below:
Inline Html Helpers – These are create in the same view by using the Razor @helper tag. These helpers can be reused only on the same view.
@helper ListingItems(string[] items)
{
- @item
@foreach (string item in items)
{
}
}
Programming Languages:
@ListingItems(new string[] { \”C\”, \”C++\”, \”C#\” })
Book List:
@ListingItems(new string[] { \”How to C\”, \”how to C++\”, \”how to C#\” })
Built-In Html Helpers – Built-In Html Helpers are extension methods on the HtmlHelper class. The Built-In Html helpers can be divided into three categories-
Standard Html Helpers – These helpers are used to render the most common types of HTML elements like as HTML text boxes, checkboxes etc. A list of most common standard html helpers is given below:
HTML Element Example
TextBox
@Html.TextBox(\”Textbox1\”, \”val\”)
Output:
TextArea
@Html.TextArea(\”Textarea1\”, \”val\”, 5, 15, null)
Output:
<textarea cols=\”15\” id=\”Textarea1\” name=\”Textarea1\” rows=\”5\”>val</textarea>
Password
@Html.Password(\”Password1\”, \”val\”)
output:
Hidden Field
@Html.Hidden(\”Hidden1\”, \”val\”)
Output:
CheckBox
@Html.CheckBox(\”Checkbox1\”, false)
Output:
RadioButton
@Html.RadioButton(\”Radiobutton1\”, \”val\”, true)
Output:
<input checked=\”checked\” id=\”Radiobutton1\” name=\”Radiobutton1\”type=\”radio\” value=\”val\” />
Drop-down list
@Html.DropDownList (“DropDownList1”, new SelectList(new [] {\”Male\”,\”Female\”}))
Output:
MF
Multiple-select
Html.ListBox(“ListBox1”, new MultiSelectList(new [] {\”Cricket\”, \”Chess\”}))
Output:
Cricket
Chess
Strongly Typed HTML Helpers – These helpers are used to render the most common types of HTML elements in strongly typed view like as HTML text boxes, checkboxes etc. The HTML elements are created based on model properties.
The strongly typed HTML helpers work on lambda expression. The model object is passed as a value to lambda expression, and you can select the field or property from model object to be used to set the id, name and value attributes of the HTML helper. A list of most common strongly-typed html helpers is given below:
HTML Element Example
TextBox
@Html.TextBoxFor(m=>m.Name)
Output:
TextArea
@Html.TextArea(m=>m.Address , 5, 15, new{}))
Output:<textarea cols=\”15\” id=\”Address\” name=\” Address \” rows=\”5\”>Addressvalue</textarea>
Password
@Html.PasswordFor(m=>m.Password)
Output:
Hidden Field
@Html.HiddenFor(m=>m.UserId)
Output:
CheckBox
@Html.CheckBoxFor(m=>m.IsApproved)
Output:
RadioButton
@Html.RadioButtonFor(m=>m.IsApproved, \”val\”)
Output:
Drop-down list
@Html.DropDownListFor(m => m.Gender, new SelectList(new [] {\”Male\”,\”Female\”}))
Output:
Male
Female
Multiple-select
Html.ListBoxFor(m => m.Hobbies, new MultiSelectList(new [] {\”Cricket\”,\”Chess\”}))
Output:Cricket
Chess
Templated HTML Helpers – These helpers figure out what HTML elements are required to render based on properties of your model class. This is a very flexible approach for displaying data to the user, although it requires some initial care and attention to set up. To setup proper HTML element with Templated HTML Helper, make use of DataType attribute of DataAnnitation class.
For example, when you use DataType as Password, A templated helper automatically render Password type HTML input element.
Templated Helper Example
Display
Renders a read-only view of the specified model property and selects an appropriate HTML element based on property’s data type and metadata.Html.Display(\”Name\”)
DisplayFor
Strongly typed version of the previous helper
Html.DisplayFor(m => m. Name)
Editor
Renders an editor for the specified model property and selects an appropriate HTML element based on property’s data type and metadata
Html.Editor(\”Name\”).
EditorFor
Strongly typed version of the previous helper
Html.EditorFor(m => m. Name)
Custom Html Helpers – You can also create your own custom helper methods by creating an extension method on the HtmlHelper class or by creating static methods with in a utility class.
public static class CustomHelpers
{
//Submit Button Helper
public static MvcHtmlString SubmitButton(this HtmlHelper helper, string buttonText)
{string str = \”<input type=\”submit\” value=\”\” + buttonText + \”\”/>\”;
return new MvcHtmlString(str);}
//Readonly Strongly-Typed TextBox Helper
public static MvcHtmlString TextBoxFor<TModel, TValue>(this HtmlHelper htmlHelper, Expression<Func<TModel,
TValue>>expression, bool isReadonly)
{MvcHtmlString html = default(MvcHtmlString);
if (isReadonly)
{html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression, new { @class = \”readOnly\”,@readonly = \”read-only\” });
}
else
{html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression);}
return html;}}
What are Url Helpers?
Url helpers allows you to render HTML links and raw URLs. The output of these helpers is dependent on the routing configuration of your ASP.NET MVC application.
HTML Element Example
Relative URL
@Url.Content(\”~/Files/asp.netmvc.pdf\”)
Output: /Files/asp.netmvc.pdf
Based on
@Html.ActionLink(\”About Us\”, \”About\”, \”Home\”)
Output: About Us
action/controller
@Html.ActionLink(\”About Me\”, \”About\”, \”Home\”, \”http\”,\”www.kansiris.org\”,null,null,null)
Output:
About Me
Raw URL for Action
Url.Action(\”About\”, \”Home\”)
Output: /Home/About
Explain attribute based routing in MVC?
In ASP.NET MVC 5.0 we have a new attribute route, By using the \”Route\” attribute we can define the URL structure. For example in the below code we have decorated the \”GotoAbout\” action with the route attribute. The route attribute says that the \”GotoAbout\” can be invoked using the URL structure \”Users/about\”.
Code:
public class HomeController: Controller
{ [Route(\”Users/about\”)]
publicActionResultGotoAbout()
{ return View(); } }
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); }
What is Razor in MVC? Or What is Razor View Engine?
Razor Engine is an advanced view engine that was introduced with MVC3. This is not a new language but it is a new markup syntax. Razor has new and advance syntax that are compact, expressive and reduces typing. Razor syntax are easy to learn and much clean than Web Form syntax. Razor uses @ symbol to write markup as:
@Html.ActionLink(\”SignUp\”, \”SignUp\”)
Why is Razor?
Compact & Expressive.
Razor minimizes the number of characters and keystroke 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.
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.
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).
Has great Intellisense.
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).
Differences between Razor and ASPX View Engine in MVC?
Razor View Engine VS ASPX View Engine:
Razor View Engine
ASPX View Engine (Web form view engine)
The namespace used by the Razor View Engine is System.Web.Razor
The namespace used by the ASPX View Engine is System.Web.Mvc.WebFormViewEngine
The file extensions used by the Razor View Engine are different from a web form view engine. It uses cshtml with C# and vbhtml with vb for views, partial view, templates and layout pages.
The file extensions used by the Web Form View Engines are like ASP.Net web forms. It uses the ASPX extension to view the aspc extension for partial views or User Controls or templates and master extensions for layout/master pages.
The Razor View Engine is an advanced view engine that was introduced with MVC 3.0. This is not a new language but it is markup.
A web form view engine is the default view engine and available from the beginning of MVC
Razor has a syntax that is very compact and helps us to reduce typing.
The web form view engine has syntax that is the same as an ASP.Net forms application.
The Razor View Engine uses @ to render server-side content.
The ASPX/web form view engine uses \”<%= %>\” or \”<%: %>\” to render server-side content.
By default all text from an @ expression is HTML encoded.
There is a different syntax (\”<%: %>\”) to make text HTML encoded.
Razor does not require the code block to be closed, the Razor View Engine parses itself and it is able to decide at runtime which is a content element and which is a code element.
A web form view engine requires the code block to be closed properly otherwise it throws a runtime exception.
The Razor View Engine prevents Cross Site Scripting (XSS) attacks by encoding the script or HTML tags before rendering to the view.
A web form View engine does not prevent Cross Site Scripting (XSS) attack.
The Razor Engine supports Test Driven Development (TDD).
Web Form view engine does not support Test Driven Development (TDD) because it depends on the System.Web.UI.Page class to make the testing complex.
Razor uses \”@* … @\” for multiline comments.
The ASPX View Engine uses \”\” for markup and \”/ … */\” for C# code.
There are only three transition characters with the Razor View Engine.
There are only three transition characters with the Razor View Engine.
The Razor View Engine is bit slower than the ASPX View Engine.
Razor provides a new view engine with streamlined code for focused templating. Razor\’s syntax is very compact and improves readability of the markup and code. By default MVC supports ASPX (web forms) and Razor View Engine. MVC also supports third-party view engines like Spark, Nhaml, NDjango, SharpDOM and so on. ASP.NET MVC is open source.
What are the Main Razor Syntax Rules?
There are following types of Razor syntax-
• 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:
@ { varmyMessage = \”Hello World\”; }
< p > The value of myMessage is: @myMessage < /p>
@ { var greeting = \”Welcome to our site!\”;
varweekDay = DateTime.Now.DayOfWeek;
vargreetingMessage = greeting + \” Here in Huston it is: \” + weekDay; }
< p > The greeting is: @greetingMessage < /p>\’>
<!-- 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>
How do you implement Forms authentication in MVC?
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\” />
</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.
Explain Areas in MVC?
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.
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:
Allows us to organize models, views and controllers into separate functional sections of the application, such as administration, billing, customer support and much more.
Easy to integrate with other Areas created by another.
Easy for unit testing.
Explain the need of display mode in MVC?
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:
We should register Display Mode with a suffix for particular browser using “DefaultDisplayMode”e class inApplication_Start() method in the Global.asax file.
View name for particular browser should be appended with suffix mentioned in first step.
-
Desktop browsers (without any suffix. e.g.: Index.cshtml, _Layout.cshtml).
-
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.
Explain the concept of MVC Scaffolding?
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.
What is Route Constraints in MVC?
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:
What is Output Caching in MVC?
The main purpose of using Output Caching is to dramatically improve the performance of an ASP.NET MVC Application. It enables us to cache the content returned by any controller method so that the same content does not need to be generated each time the same controller method is invoked. Output Caching has huge advantages, such as it reduces server round trips, reduces database server round trips, reduces network traffic etc.
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.
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.
-
Any
-
Client
-
Downstream
-
Server
-
None
-
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\”.
What is Bundling and Minification in MVC?
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.
What is Validation Summary in MVC?
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.
What is Database First Approach in MVC using Entity Framework?
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 class behaves as the link between database and controller.
There are the following approachs which is used to connect with database to application.
• Database First
• Model First
• Code First
Database first is nothing but only an 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.
What are the Folders in MVC application solutions?
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 are 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 contain methods known as \”Actions\” which responds to the user action accordingly.
Views: These are simple pages which use the model class data to populate the HTML controls and render 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 are the methods of handling an Error in MVC?
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(); }
What is Scaffolding in MVC?
Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio 2013 includes pre-installed code generators for MVC and Web API projects. You add scaffolding to your project when you want to quickly add code that interacts with data models. Using scaffolding can reduce the amount of time to develop standard data operations in your project.
Prerequisites: To use ASP.NET Scaffolding, you must have:
• Microsoft Visual Studio 2013
• Web Developer Tools (part of default Visual Studio 2013 installation)
• ASP.NET Web Frameworks and Tools 2013 (part of default Visual Studio 2013 installation)
Advantages of using Scaffolding:
Minimal or no code to create a data-driven Web applications.
Quick development time.
Pages that are fully functional and include display, insert, edit, delete, sorting, and paging functionalities.
Built-in data validation that is based on the database schema.
Filters that are created for each foreign key or Boolean fields.
What is ViewStart?
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>
What is JsonResultType in MVC?
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.
Example:
public JsonResult JsonResultTest()
{ Return Json(\”Hello My Friend!\”); }
What is TempData?
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?
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.
What is Data Annotation Validator Attributes in MVC?
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:
Required
Specify a property as required.
[Required(ErrorMessage=\”CustomerName is mandatory\”)]
RegularExpression
Specifies the regular expression to validate the value of the property.
[RegularExpression(\”[a-z]\”, ErrorMessage = \”Invalid character\”)]
Range
Specifies the Range of values between which the property values are checked.
[Range(1000,10000,ErrorMessage=\”Range should be between 1k & 10k\”)]
StringLength
Specifies the Min & Max length for a string property.
[StringLength(50, MinimumLength = 5, ErrorMessage = \”Minimum char is 5 and maximum char is 10\”)]
MaxLength
Specifies the Max length for the property value.
[MaxLength(10,ErrorMessage=\”Customer Code is exceeding\”)]
MinLength
It is used to check for minimum length.
[MinLength(5, ErrorMessage = \”Customer Code is too small\”)]
How can we done Custom Error Page in MVC?
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> </system.web>
Then, your action method needs to be marked with the atttribute.
[HandleError]
public class HomeController: Controller
{ [HandleError]
publicActionResultThrowException()
{ throw new ApplicationException(); }
