Most Asked ASP.NET MVC Questions and Answers Part-2


  1. What are Filters in MVC?
In MVC, 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.
  • 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: 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.

  1. 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"); 

} 

} 

 

  1. What are HTML helpers in MVC?
HTML helpers help you to render HTML controls in the view. For instance if you want to display a HTML textbox on the view , below is the HTML helper code.
<%= Html.TextBox("FirstName") %>
For checkbox below is the HTML helper code. In this way we have HTML helper methods for every HTML control that exists.
<%= Html.CheckBox("Yes") %>
  1. What is the difference between “HTML.TextBox” and “HTML.TextBoxFor”?
  Both provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t.     Below is a simple HTML code which just creates a simple textbox with “FirstName” as name.
Html.TextBox("FirstName ")
Below is “Html.TextBoxFor” code which creates HTML textbox using the property name ‘FirstName” from object “m”.
Html.TextBoxFor(m => m.CustomerCode)
In the same way, we have for other HTML controls like for checkbox we have “Html.CheckBox” and “Html.CheckBoxFor”.
  1. 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 call to the MapRoute() extension method of RouteCollection.
       

  1. Where is the route mapping code written?
The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax" application start event.

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

  1. What is Partial View in MVC?
 Partial view is a reusable view (like a user control) which can be embedded inside other view. For example let’s say all your pages of your site have a standard structure with left menu, header, and footer as shown in the image below.
   
For every page you would like to reuse the left menu, header, and footer controls. So you can go and create partial views for each of these items and then you call that partial view in the main view.
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

  1. How did you create a partial view and consume it?
When you add a view to your project you need to check the “Create partial view” check box.

 
Figure: Create partial view

Once the partial view is created you can then call the partial view in the main view using the Html.RenderPartial method as shown in the below code snippet:
<body>

<div>

<% Html.RenderPartial("MyView"); %>

</div>

</body>

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

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

public class HomeController: Controller 

{ 

    [Route("Users/about")] 

    publicActionResultGotoAbout() 

    { 

        return View(); 

    } 

} 
  1. What is Razor in MVC?                         
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.
  1. How to implement Forms authentication in MVC?
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.

  1. What is 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. like:

When you add an area to a project, a route for the area is defined in an AreaRegistration file. The route sends requests to the area based on the request URL. To register routes for areas, you add code to the Global.asax file that can automatically find the area routes in the AreaRegistration file.

Post a Comment

0 Comments