Showing posts with label ASP.Net MVC. Show all posts
Showing posts with label ASP.Net MVC. Show all posts

Saturday, December 21, 2013

Custom Model Validation Provider for enabling ASP.NET MVC 3 client side validation.


Implementing Custom Model Validation Provider to enable client side MVC 3 validation 

The Validation framework of ASP.NET MVC 3 is designed for extensibility and customization.  It supports validation model using attributes, or by implementing IValidatableObject or unobtrusive javascript based client side validation. It supports both property based or model based validation.

But, again ASP.Net MVC 3 assumes your solution has view models defined in a simple, flat & non hierarchical fashion to make things work. Sometimes, in applications we need to apply or perform validation rather in different ways to comply with existing legacy code, architectural style and culture.

Update: Following solution is applicable to ASP.NET MVC 3 FRAMEWORK ON VS 2010

One last word!! we assume you have in place all necessary jquery /javascript /css files for the MVC client side validation to work

Use case for Implementing Custom ModelValidatorProvider:

In my case, I did not have the pleasure to have view models exclusively defined for the mvc project.

Domain model classes are directly applied to MVC views. I cannot litter domain classes with validation attributes. They are shared components. They derive from some base classes. So, I couldn't really force annotation based validation working directly using this convoluted & hierarchical model classes as shown below:





















Binding JuniorEngineer model to mvc view and enabling property level client side validation declaratively using attributes/annotations seemed difficult for me.

Inject the validation attributes at Run time on the model:

So, we decided to inject validation attributes on model at the run time dynamically. In this case, we have to go for implementing custom validation solution which means we have to create a custom ModelValidatorProvider that allows to inject validation rules on the fly into the model.

Implementing Custom DataAnnotationsModelValidatorProvider:

MVC provides hook to plug in your custom implementation of ModelValidatorProvider. The purpose is to bind validation attributes dynamically to model to enable client side validation.

 public class JuniorEmployeeModelValidator : DataAnnotationsModelValidatorProvider
    {
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
        {
            if (metadata.ContainerType != typeof(JuniorEngineer))
                return base.GetValidators(metadata, context, attributes);
            //enable client side validation for name prop for junior engineer model. Name property is inherited from base abstract employee class.
            if (!string.IsNullOrWhiteSpace(metadata.PropertyName) && metadata.PropertyName == "Name")
            {
                //injecting required attribute to name /salary properties.
                attributes = new List<Attribute>()
                {
                    new RequiredAttribute()
                    {
                        ErrorMessage = "Hey babe, we just need a human name."
                    }
                };
            }
            if (!string.IsNullOrWhiteSpace(metadata.PropertyName) && metadata.PropertyName == "Salary")
            {
                attributes = new List<Attribute>()
                {
                    new RequiredAttribute()
                    {
                        ErrorMessage = "No one works for free!! Give him some money."
                    }
                };
            }
            return base.GetValidators(metadata, context, attributes);
        }

      
    }




Register in Global.asax:
Any customization or extension should be registered. Or You get no cookie!!












Saturday, February 14, 2009

UI Design Patterns: Model View Presenter(MVP) pattern and Model View Controller(MVC) pattern

Introduction to UI Design Patterns:

UI design patterns isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other.

There are a number of frameworks in use today that are based on these UI patterns including: JAVA Struts, ROR, Microsoft Smart Client Software Factory (CAB), Microsoft Web Client Software Factory, and the recently announced ASP.Net MVC framework.

Features of UI Design Patterns:

Loose coupling The presenter/controller are an intermediary channel between the UI code and the model. This allows the view and the model to evolve independently of each other.

Clear separation of concerns/responsibility

UI (Form or Page) – Responsible for rending UI elements

Presenter/controller – Responsible for reacting to UI events and interacts with the model

Model – Responsible for business behaviors and state management

Test Driven – By isolating each major component (UI, Presenter/controller, and model) it is easier to write unit tests. This is especially true when using the MVP pattern which only interacts with the view using an interface.

Code Reuse – By using a separation of concerns/responsible design approach you will see increase code reuse. This is especially true when using a full blown domain model and keeping all the business/state management logic where it belongs.

Hide Data Access – Using these patterns forces you to put the data access code where it belongs in a data access layer.

Flexibility/Adaptable – By isolating most of your code into the presenter/controller and model components your code base is more adaptable to change. A properly designed solution using MVC or MVP can support multi UI and data access technologies at the same time.

Let's see each of these design patterns in more details:

Model-View-Controller Design Pattern (MVC):

The MVC pattern is a popular UI architectural pattern used in application programming. This pattern separates responsibilities across three components

1) View is responsible for rending UI elements,
2) Controller is responsible for responding to UI actions,
3) Model is responsible for business behaviors and state management


The Model-View-Controller, on the other hand, provides limited capabilities for communication between the Controller and the View. MVC requires passing all data to the view in a single call

In most implementations, all these three components can directly interact with each other and in some implementations the controller is responsible for determining which view to display (Front Controller Pattern),

Model-View-Presenter Design Pattern (MVP):

The MVP pattern is another popular UI presentation pattern based on the concepts of the MVC pattern. The pattern also separates responsibilities but across four components as opposed to three in MVC world.

1) View is responsible for rending UI elements,
2) View interface is used to loosely couple the presenter from its view,
3) Presenter is responsible for interacting between the view/model through View Interface and optional service Interface
4) Model is responsible for business behaviors and state management.

Types of MVP's:

The MVP pattern is even broken down into two other patterns based on complexity into

  • Passive view
  • Supervising controller

to even more decide on how much authority the view has.

Passive MVP:

MVP is basically the MVC pattern, but it gives less control to the view and puts most of the responsibility in the presenter. It is an attempt to make all logic part of the presenter, thus making the view “passive”.

In passive mode, there won't be any event driven code to support view event handling. Instead, view would make a direct call to presenter. Due to the fact that presenter is indirectly manipulating the view elements and that the view is "dumb", there is no need for using any DTO objects because there is no need for presenter to pass any kind of data back to the view, because view doesn't do anything.

Benefits:

Simpler view-presenter wire up code where there is no need for event publishing in view or for event subscribing code in presenter.

Testability is increased because it is now much simpler to just call public presenter method to trigger that behavior instead of triggering it indirectly through simulation of the event occurrence

Supervising Controller MVP:

We tend to lean more towards the passive view, but understand it is very restricting. If I have to do a lot of data binding, I see that the supervising controller can be a more flexible pattern, but you lose a little bit of testability that you would get with the passive view.

ASP.NET MVC Framework:

It is important to understand that ASP.Net MVC is not a replacement for WebForms, it is just an alternative.

Advantages:

1) Built in MVC Pattern
2) Front Controller pattern (implemented with Routing). Note: Routing is not an ASP.Net MVC pattern. It is a new functionality, of .Net, that the ASP.Net MVC framework takes advantage of.
3) Mock testing - using a Mock framework like RhinoMock, the ASP.Net MVC allows us to mock up website objects such as server, context, etc… This is a great advantage because we don’t have to have a website actually running to do our testing.
4) No post backs or view state. This really makes .Net development more web-centric and really cleans up the html page that is ultimately created (because the view state is not in the webpage anymore)
5) Great for Agile development. It really forces you to create end to end segments, one at a time.
Disadvantages:
1) Controls support - Controls that take advantage of post backs or view state will not work. These include the data bound controls like gridview control and the AJAX controls.

2) Not great for design driven or waterfall development of large, business applications. Using something like an MVP pattern in a Web form will allow you to create interfaces and business layers completely before building any UI or View code. With ASP.Net MVC, you should create you views and test them from the beginning.

Important differences between MVC and MVP patterns:

MVP Pattern:

1) View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.

2) Easier to unit test because interaction with the view is through an interface

3) Usually view to presenter map one to one. Complex views may have multi presenters.

4) Best testability coverage of views.

5) Decouples UI completely from Data Sources

6) MVP summarized: Navigation is handled on a per page basis using page controller pattern approach.

MVC Pattern:

1) The Model-View-Controller pattern, on the contrary, assumes the View to receive user gestures and then to delegate processing to the Controller. Such a scheme comfortably fits most ASP.NET UI libraries.(Conforms to Modern UI programming)

2) Controller has a constant link to the associated View object. This allows a Controller to access its View at any moment, either by getting or setting some View properties.

3) Direct requests from the controller to the view become possible. Thus the controller itself may trigger the view updates instead of performing a round trip through the presentation model.

4) Controller are based on behaviors and can be shared across views and are based on Front Controller pattern (responsible for determining which view to display)

MVC summarized: The navigation is handled in one centralized configurable place for all the pages based on front controller pattern.

MVC pattern bypasses the standard ASP.NET request processing scheme, because the incoming gestures in MVC are received by the Controller.

Form of user requests in the ASP.NET MVC framework (which is based on a URI pattern) makes it difficult to adapt this framework to use with the conventional ASP.NET server-side event model.(doesn’t confirm to Modern UI programming)

The MVC pattern, quite the contrary, is good mainly for web applications and hardly fits other presentations. In MVC, view is aware of Model too!!

The difference between the two is just how much work the view is allowed to do. The MVP pattern attempts to take work away from the view.

Thus, if an application needs extensive communication between Controller and View objects, MVP is more preferable than MVC.

Therefore, if an application needs or later will need support for multiple GUI platforms, MVP would be the right solution.