ASP.NET MVC

ASP.NET MVC latest version information

Click ASP.NET MVC Version MVC version

1. Give ASP.NET MVC Overview.

The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. 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 authentication. The MVC framework is defined in the System.Web.Mvc assembly.

Models. Model objects are the parts of the application that implement the logic for the application's data domain. 
Views. Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data.
Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI.
For More https://msdn.microsoft.com/en-us/library/dd381412(v=vs.108).aspx

2. What is MVC Pipeline?
The following are the stages of execution for an MVC Web project.
1. Receive first request for the application
2. Perform routing
3. Create MVC request handler
4. Create controller
5. Execute controller
6. Invoke action
7. Execute result
For More https://msdn.microsoft.com/en-us/library/dd381612%28v=vs.100%29.aspx

3. What are the Core features of ASP.NET MVC?
Core features of ASP.NET MVC framework are:
4. What are Bundling and Minification?
Bundling and minification are two techniques you can use in ASP.NET 4.5 to improve request load time.  Bundling and minification 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
Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve first page load  performance. For Bundling we use bundle.config file and call method in Global.asax file.
Minification
Minification performs a variety of different code optimizations to scripts or css, such as removing unnecessary white space and comments and shortening variable names to one character. Consider the following JavaScript function.

5. What are the Action Filters?
Sometimes you want to perform logic either before an action method is called or after an action method runs. To support this, ASP.NET MVC provides filters. Filters are custom classes that provide both a declarative and programmatic means to add pre-action and post-action behavior to controller action methods.
ASP.NET MVC supports the following types of action filters:

Authorization filters- These implement IAuthorizationFilter and make security decisions about whether to execute an action method, such as performing authentication or validating properties of the request.

Action filters- These implement IActionFilter and wrap the action method execution. The IActionFilter interface declares two methods: OnActionExecuting and OnActionExecutedOnActionExecuting runs before the action method. OnActionExecuted runs after the action method.

Result filters- These implement IResultFilter and wrap execution of the ActionResult object. IResultFilter declares two methods: OnResultExecuting and OnResultExecutedOnResultExecuting runs before the ActionResult object is executed. OnResultExecuted runs after the result.

Exception filters- These implement IExceptionFilter and execute if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline. Exception filters can be used for tasks such as logging or displaying an error page. The HandleErrorAttribute class is one example of an exception filter.

6. What are ViewBag , ViewData ,TempData, Session?

ViewData - ViewData is used to pass data from controller to corresponding view.
It’s life lies only during the current request.
If redirection occurs then it’s value becomes null.
It’s required typecasting for getting data and check for null values to avoid error.
ViewData is a dictionary object that is derived from ViewDataDictionary class.
ViewData is a property of ControllerBase class.

ViewBag - ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
it is used to pass data from controller to corresponding view.
It’s life also lies only during the current request.
If redirection occurs then it’s value becomes null.
It doesn’t required typecasting for getting data.

TempData - TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
It’s required typecasting for getting data and check for null values to avoid error.
It’s life is very short and lies only till the target view is fully loaded.

SessionSession is a property of Controller class whose type is HttpSessionStateBase.
Session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it persists for its expiration time (by default session expiration time is 20 minutes but it can be increased).
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.

7. How TempData Peek and Keep works?
“TempData can also preserve values for the next request depending on 4 conditions”.
  • Not Read - If you set a “TempData” inside your action and if you do not read it in your view, then “TempData” will be persisted for the next request.
  • Normal Read - If you read the “TempData” normally like the below code, it will not persist for the next request.
stringstr = TempData[key];
  • Read and Keep - If you read the “TempData” and call the “Keep” method, it will be persisted for next request.
@TempData[key];
TempData.Keep(key);
  • Peek and Read - If you read “TempData” by using the “Peek” method, it will persist for the next request.
stringstr = TempData.Peek("Td").ToString();

8. Differentiate RenderPartial vs RenderAction vs Partial vs Action in MVC Razor.

Please refer my post Here

9. How will you create Custom Action Filters?
An action filter is implemented as an attribute class that inherits from ActionFilterAttributeActionFilterAttribute is an abstract class that has four virtual methods that you can override: OnActionExecutingOnActionExecutedOnResultExecuting, and OnResultExecuted. To implement an action filter, you must override at least one of these methods.
The ASP.NET MVC framework will call the OnActionExecuting method of your action filter before it calls any action method that is marked with your action filter attribute. Similarly, the framework will call the OnActionExecuted method after the action method has finished.
The OnResultExecuting method is called just before the ActionResult instance that is returned by your action is invoked. The OnResultExecutedmethod is called just after the result is executed. These methods are useful for performing actions such as logging, output caching, and so forth. 
10. Explain Caching and Output Cache.
Please refer my post here Caching and Output Cache

11. What is 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.

For More click Scaffolding

12. What is Attribute based Routing?
Routing is how ASP.NET MVC matches a URI to an action. MVC 5 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application. for example

[Route(“{productId:int}/{productTitle}”)]
public ActionResult Show(int productId) { … }
For more click Attribute based routing

13. What are Action Results?
Action methods typically return a result that is known as an action result. The ActionResult class is the base class for all action results. You decide which type of action result to return based on the task that the action method is performing.
A common action result is obtained by calling the View method, which returns an instance of the ViewResult class. The ViewResult derives from ActionResult. In that case, the return type of the action method is ActionResult, but an instance of the ViewResult class is returned, as shown below.
public ActionResult Index()
{
    return View();
}
The following table shows the built-in action result types and the action helper methods that return them.
Action Result
Helper Method
Description
Renders a view as a Web page.
Renders a partial view, which defines a section of a view that can be rendered inside another view.
Redirects to another action method by using its URL.
Redirects to another action method.
Returns a user-defined content type.
Returns a serialized JSON object.
Returns a script that can be executed on the client.
For More click Action Results

14. Mention what is the difference between “ActionResult” and “ViewResult” ?
“ActionResult” is an abstract class while “ViewResult” is derived from “AbstractResult” class.  “ActionResult” has a number of derived classes like “JsonResult”, “FileStreamResult” and “ViewResult” .
“ActionResult” is best if you are deriving different types of view dynamically.
15. Mention what is the importance of NonActionAttribute?
All public methods of a controller class are treated as the action method if you want to prevent this default method then you have to assign the public method with NonActionAttribute.
16. Mention what is the use of the default route {resource}.axd/{*pathinfo} ?
This default route prevents request for a web resource file such as Webresource.axd or ScriptResource.axd from being passed to the controller.
17. Mention the order of the filters that get executed, if the multiple filters are implemented?
The filter order would be like
  • Authorization filters
  • Action filters
  • Response filters
  • Exception filters

18. What is a ViewEngine in ASP.NET MVC?

“View Engine in ASP.NET MVC is used to translate our views to HTML and then render to browser.” There are few View Engines available for ASP.NET MVC but commonly used View Engines are Razor, Web Forms/ASPX, NHaml and Spark etc. Most of the developers are familiar with Web Forms View Engine (ASPX) and Razor View Engine.

  • Web Form View Engine was with ASP.NET MVC since beginning.
  • Razor View Engine was introduced later in MVC3.
  • NHaml is an open source view engine since 2007.
  • Spark is also an open source since 2008.

20. What are ASP.NET MVC HtmlHelpers?

An HTML Helper is just a method that returns a 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 <input> and <img> tags. You also can use HTML Helpers to render more complex content such as a tab strip or an HTML table of database data. Example - 
  • Html.ActionLink()
  • Html.BeginForm()
  • Html.CheckBox()
  • Html.DropDownList()
  • For Details click Html Helpers

21. What is Bootstrap in MVC5?

Bootstrap (a front-end framework) is an open source collection of tools that contains HTML and CSS-based design templates along with Javascript to create a responsive design for web applications. Bootstrap provides a base collection including layouts, base CSS, JavaScript widgets, customizable components and plugins. Project Template in ASP.NET MVC5 is now using bootstrap that enhances look and feel with easy customization.

22. What is routing in ASP.NET MVC?

Routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. At runtime, Routing engine use the Route table for matching the incoming request's URL pattern against the URL patterns defined in the Route table. You can register one or more URL patterns to the Route table at Application_Start event. MVC5 also supports attribute routing.
The following table shows valid route patterns and examples of URL requests that match the patterns.
Route definition
Example of matching URL
{controller}/{action}/{id}
/Products/show/beverages
For detail click -  Routing    Routing MSDN
23. Difference between TextBoxFor and Textbox.
The TextBoxFor is a newer MVC input extension introduced in MVC2. The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime. The main difference is that Textbox is not strongly typed.
24. How does Validation works in ASP.NET MVC?
Client Side Validation - The validation is implemented using jQuery and jQuery validation plug-in (jquery.validate.min.js and jquery.validate.unobtrusive.min.js).
With client-side validation, the input data is checked as soon as they are submitted, so there is no postback to the server and there is no page refresh.
When you are developing an MVC application in Visual Studio 2012, then the client-side becomes enabled by default, but you can easily enable or disable the writing of the following app setting code snippet in the web.config file.
<configuration>
  <appSettings>  
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
</configuration>
The jQuery validation plug-in takes advantage of the Data Annotation attributes defined in the model, which means that you need to do very little to start using it.
public class Employee
    {
        [Required(ErrorMessage = "Name is Requirde")]
        public string Name { get; set; }
        [Required(ErrorMessage = "Email is Requirde")]
        [RegularExpression(@"^([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})(\]?)$",
                            ErrorMessage = "Email is not valid")]
        public string Email { get; set; }
    }
For More Client Side Validation  Validation in MVC
Server Side Validation - Clike Here
Unobtrusive JavaScript -  is a general approach to the use of JavaScript in web pages. Though the term is not formally defined, its basic principles are generally understood to include:

25. What is CSRF attack and how can we prevent the same in MVC? what is Anti-Forgery Tokens?
For this refer my post CSRF Attack
26. What are the different techniques to handle Exceptions in ASP.NET MVC?
Please refer my post Different techniques to handle Exceptions

27. Can you remove default View Engine in ASP.NET MVC? How?

4 comments:

  1. These questions are very helpful for interview.

    ReplyDelete
  2. Sir can you please some advace question like dependancy injectin n all. These are common question

    ReplyDelete
    Replies
    1. I have given all SOLID principles and some design patterns under "Principles & Patterns" menu. please can refer that. If after that you have any doubt please let me know.

      Delete
    2. Please refer 'Dependency Inversion Principle' under Principles and Patterns menu.

      Delete