Now Article Posting by Mails By Anyone

"Training Enhancers (A division of Network Enhancers - NETEN) now introduces anyone to post the artcles related to trainings, events, knowledge sharing, Technology advances of their respective domain in a simple way by mail to - trainingenhancers.blogpost@blogger.com"
All the articles will be reviewed manullay by the Moderator and if articles were found not relevant to the Blog, those articles will be removed.

/Training Enhancers Team

Saturday, 4 August 2012

MVC Basic and Advanced Interview Questions

What is MVC?
MVC is a framework methodology that divides an application’s implementation into three component roles: models, views, and controllers.

“Models” in a MVC based application are the components of the application that are responsible for maintaining state. Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL).

“Views” in a MVC based application are the components responsible for displaying the application’s user interface. Typically this UI is created off of the model data (for example: we might create an Product “Edit” view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object).

“Controllers” in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC application the view is only about displaying information – it is the controller that handles and responds to user input and interaction.

Which are the advantages of using MVC Framework?

MVC is one of the most used architecture pattern in ASP.NET and this is one of those ASP.NET interview question to test that do you really understand the importance of model view controller.
1. It provides a clean separation of concerns between UI and model.
2. UI can be unit test thus automating UI testing.
3. Better reuse of views and model. You can have multiple views which can point to the same model and also vice versa.
4. Code is better organized.

What is Razor View Engine?

Razor view engine is a new view engine created with ASP.Net MVC model using specially designed Razor parser to render the HTML out of dynamic server side code. It allows us to write Compact, Expressive, Clean and Fluid code with new syntaxes to include server side code in to HTML.

What is namespace of asp.net mvc?

ASP.NET MVC namespaces and classes are located in the System.Web.Mvc assembly.

System.Web.Mvc namespace
Contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders.

System.Web.Mvc.Ajax namespace
Contains classes that support Ajax scripts in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings.

System.Web.Mvc.Async namespace
Contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application

System.Web.Mvc.Html namespace
Contains classes that help render HTML controls in an MVC application. The namespace includes classes that support forms, input controls, links, partial views, and validation.

How to identify AJAX request with C# in MVC.NET?

The solution is in depended from MVC.NET framework and universal across server-side technologies. Most modern AJAX applications utilize XmlHTTPRequest to send async request to the server. Such requests will have distinct request header:
X-Requested-With = XMLHTTPREQUEST
AJAX GET Request

MVC.NET provides helper function to check for ajax requests which internally inspects X-Requested-With request header to set IsAjax flag.
HelperPage.IsAjax Property
Gets a value that indicates whether Ajax is being used during the request of the Web page.
Namespace: System.Web.WebPages
Assembly: System.Web.WebPages.dll
However, same can be achieved by checking requests header directly:
Request["X-Requested-With"] == “XmlHttpRequest”

What is Repository Pattern in ASP.NET MVC?

Repository pattern is usefult for decoupling entity operations form presentation, which allows easy mocking and unit testing.

“The Repository will delegate to the appropriate infrastructure services to get the job done. Encapsulating in the mechanisms of storage, retrieval and query is the most basic feature of a Repository implementation”
“Most common queries should also be hard coded to the Repositories as methods.”

Which MVC.NET to implement repository pattern Controller would have 2 constructors on parameterless for framework to call, and the second one which takes repository as an input:
class myController: Controller
{
private IMyRepository repository;
// overloaded constructor
public myController(IMyRepository repository)
{
this.repository = repository;
}
// default constructor for framework to call
public myController()
{
//concreate implementation
myController(new someRepository());
}
...
public ActionResult Load()
{
// loading data from repository
var myData = repository.Load();
}
}

What is difference between MVC(Model-View-Controller) and MVP(Model-View-Presenter)?

The main difference between the two is how the manager (controller/presenter) sits in the overall
architecture.

All requests goes first to the Controller
MVC pattern puts the controller as the main ‘guy’ in charge for running the show. All application request comes through straight to the controller, and it will decide what to do with the request.
Giving this level of authority to the controller isn’t an easy task in most cases. Users interaction in an application happen most of the time on the View.

Thus to adopt MVC pattern in a web application, for example, the url need to become a way of instantiating a specific controller, rather than ‘simply’ finding the right View (webform/ html page) to render out. Every requests need to trigger the instantiation of a controller which will eventually produce a response to the user.

This is the reason why it’s alot more difficult to implement pure MVC using Asp.Net Webform. The Url routing system in Asp.Net webform by default is tied in to the server filesystem or IIS virtual directory structure. Each of these aspx files are essentially Views which will always get called and instantiated first before any other classes in the project. (Of course I’m overgeneralizing here. Classes like IHttpModule, IHttpHandler and Global.asax would be instantiated first before the aspx web form pages).

MVP (Supervising Controller) on the other hand, doesn’t mind for the View to take on a bigger role. View is the first object instantiated in the execution pipeline, which then responsible for passing any events that happens on itself to the Presenter.
The presenter then fetch the Models, and pass it back to the view for rendering.

What is the ‘page lifecycle’ of an ASP.NET MVC?

Following process are performed by ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view

How to call javascript function on the change of Dropdown List in ASP.NET MVC?

Create a java-script function:
<script type="text/javascript">
function selectedIndexChanged() {
}
</script>
Call the function:
<%:Html.DropDownListFor(x => x.SelectedProduct,
new SelectList(Model.Products, "Value", "Text"),
"Please Select a product", new { id = "dropDown1",
onchange="selectedIndexChanged()" })%>
 
How route table is created in ASP.NET MVC?

When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.

How do you avoid XSS Vulnerabilities in ASP.NET MVC?

Use thesyntax in ASP.NET MVC instead of usingin .net framework 4.0.

Explain how to access Viewstate values of this page in the next page?

PreviousPage property is set to the page property of the nest page to access the viewstate value of the page in the next page.
 
Page poster = this.PreviousPage;

Once that is done, a control can be found from the previous page and its state can be read.
 
Label posterLabel = poster.findControl("myLabel");
string lbl = posterLabel.Text;

How to create dynamic property with the help of viewbag in ASP.NET MVC?

PreviousPage property is set to the page property of the nest page to access the viewstate value of the page in the next page.
Page poster = this.PreviousPage;

Once that is done, a control can be found from the previous page and its state can be read.
Label posterLabel = poster.findControl("myLabel");
string lbl = posterLabel.Text;

What is difference between Viewbag and Viewdata in ASP.NET MVC?

The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.

What is Routing?

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. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.


Advanced


1. Can you describe ASP.NET MVC Request Life Cycle?
Ans.
There are two answers for the question.
Short Answer: Following are the steps that are executed in ASP.NET MVC Request Life Cycle.
I. Receive request, look up Route object in RouteTable collection and create RouteData object.
II. Create RequestContext instance.
III. Create MvcHandler and pass RequestContext to handler.
IV. Identify IControllerFactory from RequestContext.
V. Create instance of class that implements ControllerBase.
VI. Call MyController.Execute method.
VII. The ControllerActionInvoker determines which action to invoke on the controller and executes the action on the controller, which results in calling the model and returning a view.

Detailed Answer: There are five main steps occurs in ASP.NET Request Life Cycle.

I. Initialize Application (Route table is created)
Desc. When we request a page from a normal ASP.NET application, there is a physical copy of page on the disk that is corresponds to each page request. In ASP.NET MVC, there is no page on the disk that corresponds to the request. Request is routed to the controller. The controller is responsible for generating page that is sent back to the browser.

ASP.NET MVC has Route Table which stores mapping entries of particular URLs to action methods of contoller. i.e. URL “http://jinaldesai.net/Articles/CSharp” maps to the “CSharp” method of “Articles” controller.

In ASP.NET MVC application like normal ASP.NET application when application starts first time, it calls Application_Start() application event from Global.asax. Route table is registered(created) from Appication_Start() event.

II. Routing Mechanism (UrlRoutingModule intercepts the request)
When a request is coming to ASP.NET MVC application, the request is intercepted by UrlRoutingModule HTTP Module. The first thing the module does is to wrap up the current HttpContext in an HttpContextWrapper2 object. Next, the module passes the wrapped HttpContext to the RouteTable that was setup in the previous step, which includes includes the URL, form parameters, query string parameters, and cookies associated with the current request.
Next, the module creates a RouteContext object that represents the current HttpContext and RouteData. The module then instantiates a new HttpHandler based on the RouteTable and passes the RouteContext to the new handler’s constructor(In ASP.NET MVC case it is MvcHandler).
Last step taken by module is setting MvcHandler as the current HTTP Handler.

III. MvcHandler Executes (Instantiate and execute controller)
In normal ASP.NET application after second step, it fires set of events including Start, BeginRequest, PostResolveRequestCache, etc.
While in case of ASP.NET MVC application, MvcHandler(which is created in previous step) creates appropriate controller instance to serve the request by passing controller name(found through the route mapping table) and RequestContext to the static method CreateController() method of ControllerFactory class(i.e. ControllerFactory.CreateController()) to get particular controller.
Next is ControllerContext object is created from the RequestContext and the controller. And the last step in Step 3 is the Execute() method is called on the controller class.(Here factory pattern is implemented)

IV. Controller Executes (Locate and invoke controller action)
The Controller.Execute() method takes RouteData and other context information to locate appropriate action method. It also maps incoming request parameters(querystring, form, etc) to the parameter list of the controller action method.
Next is the controller calls it’s InvokeAction() method, passing details of the choosen action method and invokes the action method and our code finally runs.

V. RenderView Method Invoked (Instantiate and render view)
The controller object created in previous step has a property ViewFactory of type IViewFactory. The IViewFactory has a method CreateView(), which is called next by passing view name and other context information. The CreateView() method returns an IView.
Next the controller invokes RenderView() method of returned IView with again supplying necessary context information includes ViewData and IHttpResponse object. The response data is a HTML, an image, or any other binary or text data.

2. What is MVP?
Ans.
MVP(Model View Presentor) is a user interface design pattern engineered to facilitate automated unit testing and improve the separation of concerns in presentation logic.
It is derived from MVC(Model View Controller) design pattern. The MVP in the pattern has following description.
The model is an interface defining the data to be displayed or otherwise acted upon in the user interface.
The view is an interface that displays data (the model) and routes user commands (events) to the presenter to act upon that data.
The presenter acts upon the model and the view. It retrieves data from repositories (the model), and formats it for display in the view.
http://msdn.microsoft.com/en-us/magazine/cc188690.aspx

3. What is difference between MVC and MVP?
Ans.
The key difference between MVC and MVP is that MVP truly separates the UI from the domain/service layer of the application. In MVP the presenter assumes the functionality of the middle-man(played by the Controller in MVC). MVP is specially geared towards a page event model such as ASP.NET.
For more differences see my article: MVC Vs MVP

4. What is Application Areas in ASP.NET MVC application? Why it is necessary?
Ans.
An Area in ASP.NET MVC application is subset of the project structure based on a logical grouping. Each area contains area specific models, views and controllers. In ASP.NET MVC we can use the default project structure for most websites without having any problems. However, there are some sites that are very large; keeping all the models, views and controllers in a single folder set can be difficult to manage. For such cases, we can define different project ares in ASP.NET MVC application.

5. What are the different return types controller action method supports in ASP.NET MVC?
Ans.
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) : Used to return a webpage from an action method.
PartialviewResult (Partialview) : Used to send a section of a view to be rendered
inside another view.
RedirectResult (Redirect) : Used to redirect to another controller and action method
based on a URL.
RedirectToRouteResult (RedirectToAction, RedirectToRoute) : Used to redirect to
another action method.
ContentResult (Content) : Used to return a custom content type as the result of the
action method. This is an HTTP content type, such as text/plain.
jsonResult (json) : Used to return a message formatted as JSON.
javascriptResult (javascript) : Used to return JavaScript code that will be executed
in the user’s browser.
FileResult (File) : Used to send binary output as the response.
EmptyResult : Used to return nothing (void) as the result.

6. What is action filters in ASP.NET MVC?
Ans.
In ASP.NET MVC we can run our code before controller’s action method is executed or after the action method run. To achieve this we can use action filters. We can apply action filters by applying attributes to action methods.

7. Can you describe different types of action filters in brief?
Ans.
There are mainly three types of action filters provided in ASP.NET MVC.
Authorization Filter : It makes security decisions about whether to execute an action method, such as performing authentication or validating properties of the request. The AuthorizeAttribute class is one example of an authorization filter.
Result Filter : It wraps execution of the ActionResult object. This filter can perform additional processing of the result, such as modifying the HTTP response. The OutputCacheAttribute class is one example of a result filter.

Execution Filter : It executes if there is an unhandled exception thrown somewhere in action method, starting with the authorization filters and ending with the execution of the result. 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.
http://msdn.microsoft.com/en-us/library/dd410209.aspx

Apart from the readymade action filters provided by ASP.NET MVC, you can also implement your own action filter by inheriting ActionFilterAttribute abstract class. It has four virtual methods that you can override: OnActionExecuting, OnActionExecuted, OnResultExecuting and OnResultExecuted. To implement an action filter, you must override at least one of these methods.

http://msdn.microsoft.com/en-us/library/dd381609

8. What are the enhancements ASP.NET MVC 3 provided compared to ASP.NET MVC 2?
Ans.
There are many enhancements come with ASP.NET MVC 3. Following are list of some enhancements in ASP.NET MVC 3.
Razor View Engine
Partial Page Output Caching
Unobtrusive Javascript and Validation
New Dynamic ViewModel Property
Global Filters
New ActionResult Types (HttpNotFoundResult, HttpStatusCodeResult, HttpRedirectResult)
Built in JSON binding support

9. What is Data Annotations?
Ans.
Data Annotations are validation mechanism we can use to validate our data stored in form of Entity Data Model, LINQ to SQL or any other data models. We can use it in form of attributes to our properties of mode class. These attributes provide common validation patterns, such as range checking and required fields. Once we apply these attributes to our model class, ASP.NET MVC will provide both client and server side validation checks with no additional coding required. You can also implement your custom Data Annotation Validator by inheriting ValidationAttribute class and overriding IsValid method. To name a few there is RangeAttribute, RequiredAttribute, StringLengthAttribute, RegularExpressionAttribute, etc.
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx (Complete List of Data Annotation attributes)

10. What are HTML Helpers in ASP.NET MVC?
Ans.
In 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. To name a few there is BeginForm(), EndForm(), TextBox(), TextArea(), ListBox(), RadioButton(), etc.
http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.aspx (Complete List of HTML Helpers)

No comments:

Post a Comment