Tuesday, December 21, 2010

ASP.NET MVC Views

Views - Introduction

  • The View is responsible for providing the user interface (UI) to the user.
  • Views should not contain application and business logic.
  • View Engine is used to generate views. The default view engine is WebFormViewEngine.
  • Views in ASP.NET MVC derive from a common base class, System.Web.Mvc.ViewPage, which itself derives from System.Web.UI.Page. Strongly typed Views derive from the generic ViewPage<T>.
  • View is able to take advantage of Master Pages, one of the benefits of building on Views on top of the existing ASP.NET Page infrastructure.
  • ASP.NET MVC provides a library of helper methods used to output properly encoded HTML, which provides a lot of help in creating Views.
  • A view renders the appropriate UI by using the data that is passed to it from the controller. This data is passed to a view from a controller action method by using the View method.

View Structure

  • When we create a new ASP.NET MVC application, the project contains “Views” directory structured in a very specific way. See the following figure

                                  
  • The Views directory contains a folder per Controller, with the same name as the Controller, sans the “Controller” suffix. Within each Controller folder, there’s a View file for each action method, named the same as the action method.
  • The action method can return a ViewResult via the View method like,

public ActionResult Index()
{
ViewData["Message"] = "Welcome to Balamurugan Nattarasan Blog!";
                   return View();
          }


  • If the View name is not specified in the ViewResult then the View name same as the action name in the /Views/ControllerName directory.
  • In the above example, the View would be /Views/Home/Index.aspx.
  • The View method calls the view engine, which uses the data in the list to render to the view and to display it in the browser.
  • The View can be overridden. You want the Index action render a different then you could pass different View name like,

public ActionResult Index()
{
ViewData["Message"] = "Welcome to Balamurugan Nattarasan Blog!";
                   return View("TestMethod");
          }

  • You want to specify the View in a completely different directory structure, then you can use tilde (~) symbol to provide the full path to the View like,

public ActionResult Index()
{
ViewData["Message"] = "Welcome to Balamurugan Nattarasan Blog!";
                   return View("~/Test/TestMethod1.aspx");
          }

  • When using the tilde syntax, you must supply the file extension of the View because this bypasses the View engine’s internal lookup mechanism for finding Views.


View Pages
·         A view page is an instance of the ViewPage class. It inherits from the Page class and implements the IViewDataContainer interface.
·         The ViewPage class defines a ViewData property that returns a ViewDataDictionary object. This property contains the data that the view should display.
·         The MVC framework uses URL routing to determine which controller action to invoke, and the controller action then decides which views to render.

Master-Page Views
·         ASP.NET page views (.aspx files) can use master pages to define a consistent layout and structure. In a typical site, the master page is bound to a content page in the @ Page directive of the content page.
·         You can also use dynamic master pages (that is, you can assign a master page at run time) when you call the View method of the Controller class.

Partial Views
·         A partial view enables you to define a view that will be rendered inside a parent view. Partial views are implemented as ASP.NET user controls (.ascx).
·         When a partial view is instantiated, it gets its own copy of the ViewDataDictionary object that is available to the parent view. The partial view therefore has access to the data of the parent view.
·         However, if the partial view updates the data, those updates affect only the partial view's ViewData object. The parent view's data is not changed.

Shared Views
·         The ASP.NET MVC framework always attempts to retrieve a view from the Shared folder when the view can’t be retrieved from the Views subfolder that corresponds to the controller’s name. This means that you can create default views for action methods that are shared across multiple controllers.
·         For example HomeController exposes an action named Index(). When the Index() action is invoked, the ASP.NET MVC framework first attempts to retrieve the Index view from the following path:
\Views\Home\Index.aspx
·         If the Index.aspx view is not present in the Home folder, the ASP.NET MVC framework next attempts to retrieve the view from the Shared folder:
\Views\Shared\Index.aspx
·         If the Index.aspx view can’t be retrieved from either location, then the error message will be displayed.

Thursday, November 25, 2010

MVC Controller


MVC controllers are responsible for handling incoming HTTP requests, handling user input, retrieving and saving data, and determining the response to send back to the client.

Each browser request is mapped to a particular controller.

Controllers are derived from System.Web.Mvc.Controller (built-in controller base class).

Action

Each public method on a controller class is an action method, which means you can invoke it from the web via some URL.

A method used as a controller action cannot be overloaded.
The method must be public.
The method cannot be a static or extension method.
The method cannot be a constructor, getter, or setter.
The method cannot have open generic types.
The method is not a method of the controller base class.
The method cannot contain ref or out parameters.

A controller action can be invoked by anyone connected to the Internet.
If you don’t want to expose the method as a controller action then you can prevent the method from being invoked by using the [NonAction] attribute.

A controller action returns something called an action result. An action result is what a controller action returns in response to a browser request.

The ASP.NET MVC framework supports several types of action results including:
Action Result
Description
Controller base class method
ViewResult
Represents HTML and markup
View
EmptyResult
Represents no result

RedirectResult
Represents a redirection to a new URL
Redirect
JsonResult
Represents a JavaScript Object Notation result that can be used in an AJAX application
Json
JavaScriptResult
Represents a JavaScript script
JavaScriptResult
ContentResult
Represents a text result
Content
FileContentResult
Represents a downloadable file (with the binary content)
File
FilePathResult
Represents a downloadable file (with a path)
File
FileStreamResult
Represents a downloadable file (with a file stream)
File


Tuesday, November 23, 2010

Introduction To MVC

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 MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.

The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic. 

ASP.net MVC is an alternative approach to web forms rather than a replacement. It will not replace web forms and web forms will not replace ASP.NET MVC. The fact is that ASP.NET MVC and web forms will co-exist and that ASP.NET MVC is not a replacement for web forms.

Problems with ASP.net Web Form
·         Web forms introduced event-driven approach and also introduced Viewstate and Postback. The end result is that web forms break the stateless nature of the Web.
·         Both Viewstate and Postbacks have been made lot of problems and increased complexity of the web application development.
·         Many web pages having hundreds of KB size of Viewstate that affected the performance of the applications sometime.
·         Developers do not have the control of the rendering HTML of web forms and Server controls that render html with mixed inline style and deprecated tags that does not follows standards.
·         Another problem with Web Forms is the integration of JavaScript frameworks due to the naming conventions of rendered HTML.
·         The page life cycle of the Web Form is too complex and has the tightly coupling between all things in the ASP.net framework and a single class is used both to display output and handles user input.
·         So unit testing is almost an impossible task. Since web is a stateless thing, Events, Postbacks and Viewstate are not a good way.
·         Many ASP.net web form developers are facing different type pf browser compatibility issues when developing public face internet applications.
·         It uses a Page Controller pattern that adds functionality to individual pages.

ASP.NET MVC Approach
·         The ASP.NET MVC simplifies the complex parts of ASP.net Web Forms without any compromise of the power and flexibility of ASP.NET platform.
·         ASP.net MVC implements Model-View-Controller UI pattern for web application development that lets you allows to develop applications in a loosely couples manner.
·         MVC pattern is separating the application in three parts- Model, View and Controller.
·         A view is responsible for rendering the user interface (UI) of the application and it is nothing more than html templates that filled with application’s data passed by the controller.
·         The Model implements the logic for the application's data and it represents the business objects of the application that using the View for rendering user interface.
·         Controllers are handles and responds to user input and interaction. The web request will be handled by the controller, and the controller will decide which model objects to use and which view objects to render. The MVC model replaces the Web Form events with the controller actions.
·         The main advantages of the MVC models are clear separation of concerns, unit testing facility, and more control over the URLs and HTML.
·         The MVC model does not use Viewstate, Postbacks, Server controls, and server-based forms that enable full control over the application and html rendered by the Views.
·         MVC model is using Representational state transfer (REST) based URLs instead of file-name extensions used by the Web Form model so that we can make search engine optimization (SEO) URLs published by the application.
·         It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure.

Choose Best Approach:
·         If you want more control over the HTML or you want Test Driven Development (TDD), or you care about web standards, accessibility, or you want to build SEO based URLs, you can choose MVC model.
·         If you want rich controls and state oriented event-driven web development, you can choose Web Forms model.

MVC Features
·         You can easily integrate with jQuery and other JavaScript frameworks with MVC. Using extension methods of C# 3.0, we can make powerful and rich HTML helper methods.
·         The MVC model allows building highly testable, maintainable loosely coupled applications with good practices such as TDD, Separation of Concerns (SoC) and Dependency Injection (DI).