MVD ( Model View Dispatcher ) 4

Article-5-small

 Beginning

IML contributed greatly to a simpler way of creating ajax application due to the ability to divide complex Veiws into simple ones remarkably reducing the code and to increasing noteworthily Action in Controller.

MVD  ( model view dispatcher )  is a design pattern to execute a Command/Query without writing an Action

For example:

The code listing presents a common case when the Action returns View, Query ( GetUserDetailsQuery ) data driven. A Query hides properly most of the logic as it obtains all appropriate database and Event Broker instruments, as well as all the re-usable objects.

Refer to the example of the Action calling of View

Over time it requires to produce a Query and pass its View traversal of the Controller, as it is a simple intermediate link to be covered by tests and supported subsequently. The problem is not with creating many Action, but with their redundancy revealed after having studied the majority of scripts solved within CQRS architecture. The Controller produces a Dispatcher obtaining no advanced logic, with a few exceptions it is a typical mundane code.

Write less, do more

Consider next a new View code

Url constructing is changed in the entry, now it is not a common Url.Action, but a specific builder to create a Query-based address and paths to View

The present code will work without writing an Action significantly saving time on development and maintenance.

No More MVC ?

To answer the above question let us see how to integrate MVD into the project

  •  Create a DispatcherController (the name is of importance) inherited from the DispatcherControllerBase (set as default by version 1.1)

Note: the Assembly comprising your Command/Query as well as other classes implemented in the View can be passed as a parameter to the constructor.

DispatcherControllerBase includes the following Action:

One can construct url to perform a Push command

One can use the Url.Dispatcher to simplify building of url address

Application

MVD covers most of the frequent scenario in web-development powered by asp.net mvc.

Note: Download. the examples

  • Push for a single command

 Note: Selector can be used as values for parameters

Note: push returns the result and there is an array comprised the results of each command for the composite

  •   Push for a command composite

  Note: be aware that in case parameter-names match, the value will be the same and from the last, and an extra prefix may be attached to the name in these situations.

  • Query as Json

  •  Query as View

Note: View path is not built under the Controller in asp.net mvc, but the site root directory, to create any folder structure for View storage.  

  •  Query as File

Note: building a File requires the Query to return byte ( byte[] ) array as a result 

  • Model as View

Note: if the query is not completed via Ajax, it will result in ContentResult  rather than JSON

  • View

Note: the present way is well-suited to obtain the template via Ajax

There is a very wide range of application for the MVD, the sequel will obtain an Async method support, thus, it can be certainly argued that there are enough capabilities to develop the project without any unified additional Controller.

What has to be done if…?

Notice that lack of the Controller does not allow using attributes implemented in different scripts. Let us consider the most frequent task virtually applied for any site, namely, a test for authorization.

Within asp.net mvc the task is solved using attributes to mark those Actions (or Controller) where validation logic is described, the present task can be solved in different ways in MVD:

  • Mark with a DispatcherController attribute and in an attribute code. This method is very convenient if writing CRM system and performing all the actions with authorization

Note: the current requested address can be checked in the Allow List in the attribute code, i.e. executing the code if the address is not included into the List.

  • Use Dispatcher Event capabilities described in the article

Note: the Command/Query can be marked with attributes, which is similar to the standard asp.net mvc work

  • Implement the test for a client

The stepwise algorithm:

  1. After loading the element ( InitIncoding ) issue an Ajax query ( line 3)
  2. Check the result via OnSuccess , if the user is not authorized, choose Break
  3. If it is OnBreak, choose trigger for SignIn “leg” and give the dialogue with an authorization form
  4. If the code passes OnBreak, perform the actions to run page scripts

The code deals with most scripts and does not limit the spectrum (roles, rights, etc ) for tests, there is also а possibility to perform various tests depending on a page, i.e. constructing Home/Index and Dashboard/Index with different codes.

Vlad Kopachinsky

I am a Senior developer at Incoding Software in Russian Federation. I created the Incoding Framework for rapid development

More Posts - Website - Twitter - Facebook - LinkedIn

4 thoughts on “MVD ( Model View Dispatcher )

  1. Artur Movsesyan 20.12.2013 %I:%M %p

    Привет. Вопрос такой: как добавить ошибку к ModelState, если нет контроллера? Только изнутри Command/Query?

  2. Artur Movsesyan 20.12.2013 %I:%M %p

    А как будет выглядеть на MVD следующий сценарий?

    public ActionResult SomeAction(){
    var user = dispatcher.Query(new GetCurrentUserQuery());
    if(user.IsManager)
    return View();
    return RedirectToAction("AnotherAction");
    }

    • Vlad Kopachinsky 20.12.2013 %I:%M %p

      Можно так :

      @(Html.When(JqueryBind.Click)
      .Do()
      .AjaxGet(Url.Dispatcher().Query(new SomeQuery()))
      .OnSuccess(dsl =>
      {
      dsl.Utilities.Document.RedirectTo("redirectUrl")
      .If(r => r.Data(r => r.IsUser));
      dsl.Utilities.Document.RedirectTo(Url.Dispatcher().AsView("SomeView"))
      .If(r => r.Data
      (r => r.IsUser == false));
      })
      .AsHtmlAttributes()
      .ToButton("Test"))

      Бывают ситуации, когда возможностей MVD не хватает, но Вы всегда можете написать свой Action. Особенность MVD в том, что он не перекрывает MVC, а дополняет. Пока большинство сценариев решаются с применением MVD, но я постоянно занимаюсь развитием функциональной части.

      P.S. Спасибо за интересные вопросы, если у Вас будут ещё сценарии, которые Вы видите нерешаемыми в рамках MVD пишите, буду благодарен. Примеры сценариев и их решение, я позже добавлю в основную статью.

Leave a Reply