Design Patterns – MVC Pattern Samples for Beginners

It explains about what is MVC Pattern and what is ASP.NET MVC Framework how it works. Also explains ASP.NET MVC page life cycle and ASP.NET MVC features version wise.

Design Patterns – MVC Pattern Samples for Beginners

Samples provided steps wise to help beginners to understand easily and become proficient in ASP.NET MVC.

As we all know many design patterns and using them in implementing business components and services in our applications but still we will be facing issues/challenges with our applications. Also day by day business needs and priorities will be changing. If we closely observe a number of issues, defects and challenges we are facing is in UI and presentation layers. Though some defects are related to business logic and business rules we may need to fix them in UI and presentation layers as we might tightly integrated business logic in UI and presentation tiers. The reason behind this is we haven’t focused on implementing right design pattern in our applications. Let us go through step by step and understand how to implement and use presentation pattern in our applications.

Problem Statement:
  1. Already using different patterns in application but still maintaining application is difficult.
  2. Using VS Test, NUnit, MBUnit etc to test business logic layer, but still some defects are exists in the application as business logic involved in presentation layer.
  3. Used Presentation Layer, Business Logic Layer, Data Access Layer in the application but still sometimes need to write redundant code in presentation layer to consume or call other modules or other use cases.
  4. Integration defects are getting injected when we make some changes in integrated modules.
  5. Defect fixing and enhancements are taking more time to analyze the presentation tier logic and its integration dependencies and causing for opening new defects.
  6. ASP.NET MVC cannot be chosen as UI is complex to build.
Root Cause of the Problem:

In Presentation layer,

  1. A page or form contains controls that display application domain data. A user can modify the data and submit the changes. The page retrieves the domain data, handles user events, alters other controls on the page in response to the events, and submits the changed domain data. Including the code that performs these functions in the Web page In addition, it is difficult to share code between Web pages that require the same behavior. the class complex, difficult to maintain, and hard to test.
  2. UI Layer, UI Logic, Presentation Logic, Business Logic are tightly coupled.
  3. Presentation layer is taking care of integrating modules or use cases.
Solution:
  1. Chose a best Presentation Layer Pattern to separate the UI Layer, UI Logic and Presentation Logic and Business Logic as separate layers to make the code easier to understand and maintain.
  2. Enable loose coupling while developing modules or any use cases.
  3. Maximize the code that can be tested with automation. (Views are hard to test.)
  4. Share code between pages that require the same behavior.
  5. Separate the responsibilities for the visual display and the event handling behavior into different classes named, respectively, the view and the presenter or controller or ViewModel.
Benefits of using Presentation Pattern:
  1. Modularity
  2. Test driven approach – maximize the code that can be tested with automation
  3. Separation of concerns
  4. Code sharing between pages and forms
  5. Easy to maintain

What are the presentation layer patterns available?

MVC (Model View Controller)

MVP (Model View Presenter) or (Model Passive View, Supervisor Controller)

MVVM (Model View ViewModel)

MVC vs MVP vs MVVM:
  1. Model and View represents same in all the above 3 patterns?

    Yes

  2. Controller, Presenter, and ViewModel purpose is same in all the above 3 patterns?

    Yes

  3. Communication and flow of Model, View with Controller, Presenter, and ViewModel is same?

    No, that is the reason these 3 patterns exists.

  4. Are these patterns replacement of PL (Presentation Layer), BLL (Business Logic Layer) and DAL (Data Access Layer)

    No, these patterns are for separating the UI and UI Logic from Presentation Logic and enables the loose coupling.

Choose the best Presentation Layer Pattern:

MVP

  1. Binding via a datacontext is not possible
  2. Complex UI Design
  3. Best for Windows Forms, ASP.NET Web Forms & Sharepoint Applications

MVC

  1. Best for ASP.NET with Simple UI
  2. Disconnected Model (View separation from all other layers)

Note: Here I am not focusing on MVC VM (MVC ViewModel from MVC3) and ASP.NET MVVM with Dependency Injection.

MVVM

  1. Binding via a datacontext is possible
  2. Connected Model
  3. Best for WPF and Silverlight applications
ASP.NET Web Forms vs ASP.NET MVC:

ASP.NET Web Forms

  1. RAD
  2. More easy development
  3. Rich controls ecosystem
  4. Familiar as the development approach to Windows Forms development
  5. No ViewState & No postback support

ASP.NET MVC

  1. Clean Separation of Concern (SoC)
  2. Full markup control
  3. Enable TDD (Test Driven Development)
  4. Enable and makes easily REST
  5. More easy client-side integration (Javascript)
  6. Multi View Engine (this is really cool!)
  7. No ViewState & No postback support
  8. Extensible and WEB 2.0 Enabled

Model, Views & Controller

  • Model: Model objects are the parts of the application that implement the logic for the application s data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in SQL Server.
  • Views: Views are the components that display the application’s user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and checkboxes based on the current state of a Products object.
  • Controller: Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn queries the database by using the values.
ASP.NET MVC High Level Page Life Cycle?

ASP.NET MVC High Level Page Life Cycle

ASP.NET MVC Low Level Page Life Cycle?

ASP.NET MVC Low Level Page Life Cycle

MVC2.0 New Features

1. Templated Helpers:

Templated Helpers helps us to automatically associate HTML elements for edit and display with data types.

E.g when data of type System.DateTime is displayed in a view, a datepicker UI element can be automatically rendered.

This is similar to how field templates work in ASP.NET Dynamic Data.

2. Areas:

Using areas We can organize a large project into multiple smaller sections in order to manage the complexity of a large Web application.

Each section (“area”) typically represents a separate section of a large Web site and is used to group related sets of controllers and views.

E.g.

Areas
	Admin
   	Controllers
   	Models
   	Views
	Iniala Claims
   	Controllers
   	Models
   	Views
3. Support for Asynchronous Controllers:

ASP.NET MVC2 allows controllers to process requests asynchronously.

This can lead to performance gains by allowing servers which frequently call blocking operations (like network requests) to call non-blocking counterparts instead.

4. Support for DefaultValueAttribute in Action-Method Parameters:

The System.ComponentModel.DefaultValueAttribute class allows a default value to be supplied for the argument parameter to an action method.

For example, assume that the following default route is defined:

{controller}/{action}/{id}

Also assume that the following controller and action method is defined:

public class ArticleController
{
  public ActionResult View(int id, [DefaultValue(1)]int page)
  {
  }
}

Any of the following request URLs will invoke the View action method that is defined in the preceding example.

  • /Article/View/123
  • /Article/View/123?page=1 (Effectively the same as the previous request)
  • /Article/View/123?page=2
5. Support for binding Binary Data with Model Binders:

There are two new overloads of the Html.Hidden helper that encode binary values as base-64-encoded strings:

public static string Hidden(this HtmlHelper htmlHelper, string name, Binary value); 
public static string Hidden(this HtmlHelper htmlHelper, string name, byte[] value);
6. Support for DataAnnotations Attributes:

Using the RangeAttribute, RequiredAttribute, StringLengthAttribute, and RegexAttribute validation attributes (defined in the System.ComponentModel.DataAnnotations namespace) when we bind to a model in order to provide input validation.

using System.ComponentModel.DataAnnotations;
namespace MvcTmpHlprs
{
	[MetadataType(typeof(ProductMD))]
	public partial class Product 
	{
    	public class ProductMD
    	{
        	public object SellStartDate { get; set; }
        	[UIHint("rbDate")]
        	public object SellEndDate { get; set; }
        	[DataType(DataType.Date)]
        	public object DiscontinuedDate { get; set; }
        	[ScaffoldColumn(false)]
        	public object ModifiedDate { get; set; }
        	[ScaffoldColumn(false)]
        	public object rowguid { get; set; }
        	[ScaffoldColumn(false)]
        	public object ThumbnailPhotoFileName { get; set; }
    	}
	}
}
7. Model-Validator Providers:

The model-validation provider class represents an abstraction that provides validation logic for the model.

ASP.NET MVC includes a default provider based on validation attributes that are included in the System.ComponentModel.DataAnnotations namespace.

8. Client-Side Validation:

The model-validator provider class exposes validation metadata to the browser in the form of JSON-serialized data that can be consumed by a client-side validation library.

ASP.NET MVC 2 includes a client validation library and adapter that supports the DataAnnotations namespace validation attributes noted earlier.

9. New RequireHttpsAttribute Action Filter:

ASP.NET MVC 2 includes a new RequireHttpsAttribute class that can be applied to action methods and controllers.

By default, the filter redirects a non-SSL (HTTP) request to the SSL-enabled (HTTPS) equivalent.

10. Overriding the HTTP Method Verb:

When we build a Website by using the REST architectural style, HTTP verbs are used to determine which action to perform for a resource.

REST requires that applications support the full range of common HTTP verbs, including GET, PUT, POST, and DELETE.

ASP.NET MVC 2 includes new attributes that we can apply to action methods and that feature compact syntax.

These attributes enable ASP.NET MVC to select an action method based on the HTTP verb.

For example, a POST request will call the first action method and a PUT request will call the second action method.

[HttpPost]
 public ActionResult Edit(int id)
 
[HttpPut]
 public ActionResult Edit(int id, Tag tag)

In earlier versions of ASP.NET MVC, these action methods required more verbose syntax, as shown in the following Example:

    	[AcceptVerbs(HttpVerbs.Post)] 
    	public ActionResult Edit(int id) 
 
    	[AcceptVerbs(HttpVerbs.Put)] 
    	public ActionResult Edit(int id, Tag tag) 

Because browsers support only the GET and POST HTTP verbs, it is not possible to post to an action that requires a different verb. Thus it is not possible to natively support all RESTful requests.

However, to support RESTful requests during POST operations, ASP.NET MVC 2 introduces a new HttpMethodOverride HTML helper method.

This method renders a hidden input element that causes the form to effectively emulate any HTTP method.

For example, by using the HttpMethodOverride HTML helper method, we can have a form submission appear be a PUT or DELETE request.

The behavior of HttpMethodOverride affects the following attributes:

  • HttpPostAttribute
  • HttpPutAttribute
  • HttpGetAttribute
  • HttpDeleteAttribute
  • AcceptVerbsAttribute
11. New HiddenInputAttribute Class for Templated Helpers:

We can apply the new HiddenInputAttribute attribute to a model property to indicate whether a hidden input element should be rendered when displaying the model in an editor template (The attribute sets an implicit UIHint value of HiddenInput).

The attribute’s DisplayValue property lets we specify whether the value is displayed in editor and display modes.

When DisplayValue is set to false, nothing is displayed, not even the HTML markup that normally surrounds a field.

The default value for DisplayValue is true.

We might use HiddenInputAttribute attribute in the following scenarios:

  • When a view lets users edit the ID of an object and it is necessary to display the value as well as to provide a hidden input element that contains the old ID so that it can be passed back to the controller.
  • When a view lets users edit a binary property that should never be displayed, such as a timestamp property.

In that case, the value and surrounding HTML markup (such as the label and value) are not displayed.

E.g:

public class ProductViewModel
{
	[HiddenInput] // equivalent to [HiddenInput(DisplayValue=true)]
	public int Id { get; set; } 
 
	public string Name { get; set; } 
 
	[HiddenInput(DisplayValue=false)] 
	public byte[] TimeStamp { get; set; }
}
12. Html.ValidationSummary Helper Method Can Display Model-Level Errors:

Instead of always displaying all validation errors, the Html.ValidationSummary helper method has a new option to display only model-level errors.

This enables model-level errors to be displayed in the validation summary and field-specific errors to be displayed next to each field.

13. T4 Templates in Visual Studio Generate Code that is Specific to the Target Version of the .NET Framework:

A new property is available to T4 files from the ASP.NET MVC T4 host that specifies the version of the .NET Framework that is used by the application.

This enables T4 templates to generate code and markup that is specific to a version of the .NET Framework.

In Visual Studio 2008, the value is always .NET 3.5. In Visual Studio 2010, the value is either .NET 3.5 or .NET4.

14. API Improvements:

Added a protected virtual CreateActionInvoker method in the Controller class.

This method is invoked by the ActionInvoker property of Controller and allows for lazy instantiation of the invoker if no invoker is already set.

Like it? Share it.

Leave a Comment Yourself

Your email address will not be published. Required fields are marked *