MVC: choosing a view at runtime - apache-flex

I'm quite new to the MVC design-pattern, and I'm translating all of my old code.
I want to move to this pattern because I can change my views according to my needs, but I'm finding difficult to do it at runtime.
I found an excellent example of MVC, and all that I do is the following:
<mx:ViewStack xmlns:mx="http://www.adobe.com/2006/mxml" resizeToContent="true" xmlns:views="MVC.views.*">
<views:HomeView id="Home"/>
<views:SecondPage id="SecondPage "/>
</mx:ViewStack>
what if I wanted to change (whenever the Controller says so) one of the views, for example the SecondPage view?
(Hope I made my point clear)

In Flex it is generally considered good practice to avoid holding direct references to your view components in your controller layer. The most common way to update views is by data binding. MATE is, in my opinion, the best Flex framework for this because it makes it very easy to inject data into views in a loosely coupled way.
However, if you actually bind to a variable holding a selectedIndex for your view stack, you are putting presentational knowledge into your model, which is also undesirable. An alternative solution is to set-up event handlers in your views that respond to events occurring elsewhere in your application and update themselves. MATE has ListenerInjectors which you can use in an event map to wire the view to the event.

Use some MVC framework like Cairngorm or Mate to begin with
Besides that you can have a model which maintains state of the application and bind selected index of ViewStack to it.

Related

How does ObjectDataSource relate to traditional MVC pattern?

(Apologies for the vagueness of this question. It is the result of some muddy thinking on my part.)
I am designing a small website with an MSSQL DB. I have just stumbled across the ObjectDataSource class. I think I understand it, but I don't see how it relates to the traditional MVC design pattern, if at all.
The class, according to Microsoft, is designed to sit between the UI (View) and the database, and as such, I would think of it as a Controller. It does indeed map UI actions to behaviours, but it also contains code for writing to the database, which is not something I would expect a Controller to do (but I may be wrong).
It seems to me that it is both the Controller and the Model, but I get the feeling I am not seeing something here.
That's a lot of words to say I am very confused. I would be very grateful to anyone who can point me at anything that might help me to understand what I am missing here.
The purpose of the ObjectDataSource is to intermediate between the view and some code that retrieves your data, not to the database directly. It is not a controller, but something that would call your code to get the data. A better description would be from an MVP scenario, where in MVP the view can manage itself, and the ObjectDataSource is a control that makes that management easier. However, the ObjectDataSource may make it harder to work with a traditional MVP or MVC design implementation out of the box, depending on the framework setup.
I personally don't like this control; I never use it as I'd rather code it so it's easier to see how the binding takes place, in addition to when the binding takes place. My personal opinion.
ObjectDataSource is not used in asp.net MVC if that's what you mean "traditional MVC design pattern". It's used primarily in WebForms development.
It's usually dropped onto a webform component and configured via the UI, although it doesn't have to be. It provides an abstraction that allows other WebForms controls to interact with an object model in a manner that is similar to the way in which these controls work with Databases. This object model may ultimately come from a database, but it allows you to insert your own database methodology in between.
WebForms does not lend itself to the traditional MVC pattern due to some technical issues which complicate using it in that way. A cleaner pattern for use with WebForms is the MVP (Model View Presenter) pattern.

Why do Presenters attach to View events instead of View calling Presenter Methods in most ASP.NET MVP implementations?

I noticed that in the Webforms MVP implementation and most other examples, the Presenter usually attaches handlers to View events. Why can't the Views just call methods in the presenter directly? Just wondering, since the whole task of attaching a handler to an event, defining EventArgs for special parameters, checking if the event is null on the view side seems a lot more tedious than just calling a method.
Sure they can, and I find that to be the best middle ground. What you are describing is I believe called Observing Presenter style. This allows you to completely decouple View from the Presenter, making the view less susceptible to changes within presenter. But it also introduces complexity in testing, and that is the reason to use MVP to begin with. I would not bother with this style at all. On very large project we use Encapsulated Presenter style, where View has a reference to Presenter, injected via IoC container, and view just calls methods on the Presenter. Easy to understand, easy to debug, easy to test.

MVP - Should views be able to call presenter methods directly or should they always raise events?

I've been using the MVP pattern for a while with ASP.NET. I've stuck to the defined pattern of raising presenter events from the view.
It has struck me that I could expose methods in the presenter that the view could call directly.
Technically, using direct methods calls would require less code. The other benefit is that I tend to share presenters across multiple views that offer similar functionality. This means that sometimes some of the event handlers are forced to be registered in a view, only to comply with the shared presenter's interface, but then are not used in that particular view at all.
A example of this would be a diary view, that in one view allows you to cancel an appointment, and in another it doesn't. The rest of the presenter events for loading the data, and saving an appointment are used in both. I don't want to write two separate presenters that almost offer the same functionality.
I'd like to hear what others think who are actively using MVP. Are there any reasons you can think of why direct method calls from the view to the presenter are bad in MVP?
I use direct method calls, and don't see any worhtwhile reason to be defining events on the presenter. What you are using with events is called I believe "Observing Presenter" style. It does offer complete decoupling of View from Presenter, but with added complexity.
We can write an interface which contains all methods that we want to call from view. Presenter will implement this interface. We can then pass instance of this interface to view, and view can call methods on this interface. This will reduce coupling between two.
If your view calls the presenter directly, then it would be tightly coupled like in mvc. I don't understand why some frameworks take this approach as opposed to raising events on the view.

Implementing paging using MVP

How to implement paging in ASP.NET webforms when applying the MVP pattern? I'm wondering where to put the paging logic...in the view or in the presenter? Also a neet way to implement paging in ASP.NET is to use the PagedDataSource control... would it be correct to use that from a presenter or would we better of implementing some custom paging logic. The data is displayed in the view using a Repeater control.
I don't know exactly, what difference is there between mvp and mvc, so I think this post might be useful to you. I personally like the idea to create a hepler outside model or controller(presenter?). Also jquery paging mechanism is pretty straight forward. In presenter just add parameters for requested rows of data and return only those instead of whole table/grid/whatever.
I think both the View and the Presenter need to know about paging. Here's why:
Intelligent paging should only retrieve data needed to fill a page. This is a collaboration between the Presenter and the Model in my mind. In pedantic MVP, the View has no knowledge of the Model, so the Presenter must be the go-between. In MVC, you might get away with excluding the Controller with a strong enough domain model.
The View needs to know about paging so that the user can interact properly with the paging metaphore (Next, Prev, proper rendering, etc)
I'm not terribly familiar with the PagedDataSource. If you're using WebForms, you're probably hosed if you want to stick to a faithful implementation of MVP. Perhaps you could set up the page caching for the PagedDataSource (if there is such a thing) in the Presenter and the GUI glamour in the View. It would mean passing around a reference to a user control, but maybe that's okay.
Kudos to you for trying to make MVP work with WebForms. I'd love to hear how it turns out.

What is the unit of reusability in .NET MVC apps?

In traditional ASP.NET Web Form applications, UserControls are a great way to encapsulate functionality so that it can be reused. However, UserControls don't fit well into the MVC model. They often make heavy use of ViewState and they blur the seperation of concerns that MVC promotes.
My question is, how do you best bundle a piece of functionality so it can be shared across MVC applications?
As an example, consider a from/to date-selector UserControl that:
allows a user to select two dates, either using a javascript overlay or by typing in day, month and year into seperate fields
can be configured to default to either today and tomorrow's dates or to dates of the developer's choosing
validates the dates that comes back from the user to ensure the from date is before the to date
exposes From and To properties that can be accessed by code-behind
How would I best build something like this in .NET MVC so that I can easily reuse it?
Note that to fully emulate User Control's functionality the MVC component would have to manage the submitted form data and validation - not just the presentation.
In general I would agree that user controls are nice in terms of encapsulating UI stuff, but I don't think too much has really changed in MVC. If I remember right re-using user controls across classic Asp.net projects was a pain and was never really the best way to truly create reusable components. Most UI toolkits that you bought for classic ASP.net didn't give you user controls, they gave you essentially server controls and javascript controls.
In your example, I would probably create or find a jquery (or ur framework of choice) plugin that did what you wanted on the client side. You could also build a C# wrapper around it similar to what Telerik did with some of the jquery UI controls. I do think that the word code-behind and even viewstate will disappear from your vocabulary the more you get into MVC.
If you look at what open source projects are out there for MVC you will get your answer in terms of what you should be doing.
The MVC Contrib app adds a lot of features by creating extension methods and helpers. Their grid control is a typical way to create a reusable component that you could use across projects
Telerik, created some extensions that wrap jquery controls and do asset management.
Finally I think if you look to the future, MVC has areas, which if I interpret it right will give you the ability to break your project apart into multiple smaller projects.
Besides what is already suggested, ASP.NET MVC v2 will have generic templated input controls, see here. You can read how other people do similar techniques, for example, here:
We have
exactly 1 method call for generating a
form element, “Html.InputFor”. As
part of that “InputFor”, it examines
an input specification, that collects
the PropertyInfo, any attributes, the
type, any modifiers called, and
selects an appropriate InputBuilder.
Call InputFor(p => p.Id) and Id is a
GUID? That creates a hidden input
element. Call InputFor(p =>
p.Customer.Address) and Address is a
complex type? That looks for a
partial with the same name of the type
Having considered the helpful answers from others, I will have a go at answering my own question.
It seems to me that the key difficulty with emulating UserControls in MVC is that they crosscut the concerns that MVC aims to seperate. The from/to date selector UserControl in my example incorporates elements of Model, View, Control and interation. UserControls' ability to bundle all this together is exactly the reason that they don't fit well into MVC.
That means that to create a psuedo-UserControl in MVC requires four seperate pieces:
A Model class - in this case an Interval class or similar
A PartialView that knows how to render the Model to HTML
A jQuery script to layer interactivity on top of the PartialView's HTML
A ModelBinder that can deserialise postdata into an instance of the Model class.
The ModelBinder is important because it deals with data coming back from the user. Without it, every Controller that wanted to display a to/from date selector in any of its Views would have to know how to assemble the six postdata fields - and how to cope if they were invalid or some were missing.
Two ways that I can think of. A partial view though this doesn't really transfer well from app to app because you are moving around ascx files. Not a big pain but not my flavour.
I prefer to use WebControls. They are super easy in mvc and all you need to do is reference the library in the project and possibly in your config file and there you go.
I think some of the answers have missed out on the postback functionality of controls. One way you could handle that is to pass any generic information via ViewData when rendering your partial view. That could then post back to its own control, which in turn could redirect to the UrlReferrer.
Its a little messy and use of UrlReferrer poses a security risk. But it is one way around the problem
You can create a jQuery plugin.
As user-controls provided in ASP.NET Webforms, MVC provide a lot of ways to make the controls and code that can be reused in other app.
Using Partials If your partial code have some C# logic and render the html using Razor/aspx code then it's bst to maintain them in razor file.
Write JavaScript Functionality as plugin If you maintain your code and write it as better as it can be used in other app then it would be a huge advantage for you. Next time when you work on other app just open this solution copy it and modify it. Write JavaScript code that can be used as plugin maybe take some more brainstorming.
Write Code As a Separate C# library If some code is too common for every app you make.for example you write a member authentication system or some global function (C#) that are used in every app you made then maintain them in a separate solution so it can be used in other app you made whenever you trying to make a new app in future.

Resources