Thursday 24 May 2012

FAQ's - ASP.NET MVC

What are the 3 main components of an ASP.NET MVC application?

“ASP.NET MVC is the evolution of Classic ASP, adding an easier separation of concerns while not using an event based model like WebForms.”
1. M - Model
2. V - View
3. C - Controller

In which assembly is the MVC framework defined?
System.Web.Mvc

Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?
Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.

What does Model, View and Controller represent in an MVC application?
Model: Model represents the application data domain. In short the applications business logic is contained with in the model.

View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.

Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.

What is the greatest advantage of using asp.net mvc over asp.net webforms?
It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET Webforms?
ASP.NET MVC

What are the advantages of ASP.NET MVC?
1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
2. Complex applications can be easily managed
3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.
4. ASP.NET MVC views are light weight, as they donot use viewstate.

Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?
Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.

Is it possible to share a view across multiple controllers?
Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.

What is the role of a controller in an MVC application?
The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render.

Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax

Name a few different return types of a controller action method?
The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult

What is the significance of NonActionAttribute?
In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.

What is the significance of ASP.NET routing?
ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.

What are the 3 segments of the default route, that is present in an ASP.NET MVC application?
1st Segment - Controller Name
2nd Segment - Action Method Name
3rd Segment - Parameter that is passed to the action method

Example: http://pragimtech.com/Customer/Details/5
Controller Name = Customer
Action Method Name = Details
Parameter Id = 5

ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are these 2 places?
1. Web.Config File : ASP.NET routing has to be enabled here.
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.

What is the adavantage of using ASP.NET routing?
In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get page not found error.

An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users.

What are the 3 things that are needed to specify a route?
1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.
2. Handler - The handler can be a physical file such as an .aspx file or a controller class.
3. Name for the Route - Name is optional.

Is the following route definition a valid route definition?
{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.

What is the use of the following default route?
{resource}.axd/{*pathInfo}
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.

What is the difference between adding routes, to a webforms application and to an mvc application?
To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, where as to add routes to an MVC application we use MapRoute() method.

How do you handle variable number of segments in a route definition?
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.
controller/{action}/{*parametervalues}

Explain different return types in controllers?


ActionResult is an abstract class that can have several subtypes:

a) ViewResult - Renders a specifed view to the response stream
b) PartialViewResult - Renders a specifed partial view to the response stream
c) EmptyResult - An empty response is returned
d) RedirectResult - Performs an HTTP redirection to a specifed URL
e) RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
f) JsonResult - Serializes a given ViewData object to JSON format
g) JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
h) ContentResult - Writes content to the response stream without requiring a view
i) FileContentResult - Returns a fle to the client
j) FileStreamResult - Returns a fle to the client, which is provided by a Stream
k) FilePathResult - Returns a fle to the client

What are the 2 ways of adding constraints to a route?
1. Use regular expressions
2. Use an object that implements IRouteConstraint interface

Give 2 examples for scenarios when routing is not applied?
1. A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true.
2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.

Difference Between ViewBag and ViewData in MVC 3?

View Data
View Bag
ViewData is a dictionary of objects that are accessible using strings as keys. This means that we will write code like this:
ViewBag uses the dynamic feature that was added in to C# 4. It allows an object to dynamically have properties added to it. The code we write using ViewBag will look like this:
In Controller

public ActionResult Index()
{
    var softwareDevelopers =
new List<string>
    {
       
"Brendan Enrick",
       
"Kevin Kuebler",
       
"Todd Ropog"
    };

    ViewData[
"softwareDevelopers"] = softwareDevelopers;

   
return View();
}
In View
<ul>
@foreach (var developer in (List
<string>)ViewData["softwareDevelopers"])
{
   
<li>
        @developer
   
li>
}
ul>
Notice that when we go to use out object on the view that we have to cast it since the ViewData is storing everything as object. Also, we need to be careful since we’re using magic strings to access these values.
In Controller

public ActionResult Index()
{
    var softwareDevelopers =
new List<string>
    {
       
"Brendan Enrick",
       
"Kevin Kuebler",
       
"Todd Ropog"
    };

    ViewBag.softwareDevelopers = softwareDevelopers;

   
return View();
}

In View
<ul>
@foreach (var developer in ViewBag.softwareDevelopers)
{
   
<li>
        @developer
   
li>
}
ul>
Notice here that we did not have to cast our object when using the ViewBag. This is because the dynamic we used lets us know the type. Keep in mind that these dynamics are as the name suggest, dynamic, which means that you need to be careful as these are basically magic properties instead of magic strings.



Difference Between ASP.NET WebForms and ASP.NET MVC?
ASP.NET WebForms
ASP.NET MVC
Uses the ‘Page Controller’ pattern. Each page has a code-behind class that acts as a controller and is responsible for rendering the layout.Uses the ‘Front Controller’ pattern. There is a single central controller for all pages to process web application requests and facilitates a rich routing architecture
Uses an architecture that combines the Controller (code behind) and the View (.aspx). Thus the Controller has a dependency on the View. Due to this, testing and maintainability becomes an issue.ASP.NET MVC enforces a "separation of concerns". The Model does not know anything about the View. The View does not know there’s a Controller. This makes MVC applications easier to test and maintain
The View is called before the Controller.Controller renders View based on actions as a result of the User Interactions on the UI.
At its core, you ‘cannot’ test your controller without instantiating a View. There are ways to get around it using tools.At its core, ASP.NET MVC was designed to make test-driven development easier. You ‘can’ test your Controller without instantiating a View and carry out unit-tests without having to run the controllers in an ASP.NET process.
WebForms manage state by using view state and server-based controls.ASP.NET MVC does not maintain state information by using view state
WebForms supports an event-driven programming style that is like Windows applications and is abstracted from the user. The State management is made transparent by using sessions, viewstate etc. In the process, the HTML output is not clean making it difficult to manage later. The ViewState also increases your page size.In ASP.NET MVC, the output is clean and you have full control over the rendered HTML. The orientation is towards building standard compliant pages and provides full control over the behavior of an application.
Deep understanding of HTML, CSS and JavaScript is not required to a large extent since the WebForm model abstracts a lot of these details and provides automatic plumbing. While abstracting details to provide ease of use, sometimes a solution is overcomplicated, than it needs to be.A thorough understanding of how HTML, CSS and JavaScript work together is required. The advantage is you can do a lot of jQuery and AJAX stuff in an efficient and simple manner than you would do in an ASP.NET application.
WebForms can drastically reduce time while building up intranet and internet applications that use a lot of controls (drag and drop model). Although this is true for development, a lot of time is spent later to code around limitations.You lose the 'drag and drop' quick model of building your web applications. The focus is on control over the application behavior and test-driven development. The model is extensible and you do not have to spend time working around limitations.
Relatively simple to learn and pickup. Works very well for developers who initially have trouble with the HTTP/HTML model and are coming from a similar WinForms oriented event model.There is a learning curve to understand the why, when and how of ASP.NET MVC.
Lesser amount of code is required to build webapps since a lot of components are integrated and provided out of the box. You can also use a lot of data controls provided out of the box that rely on ViewState.Since the application tasks are separated into different components, amount of code required is more. Since ASP.NET MVC does not use ViewState, you cannot use Data controls like GridView, Repeater.
Works very well for small teams where focus is on rapid application developmentWorks well for large projects where focus in on testability and maintainability.

No comments:

Post a Comment