Louise
Louise

Reputation: 117

MVC Model Notifying View of changes

I'm trying to develop a very simple messaging form (MVC C# forms), in which a form displays how many unread messages a user has. If a new message was to come into the list in my model, how do you notify the view (which methods)? I can't seem to get my head round this.

Upvotes: 1

Views: 2224

Answers (2)

w.donahue
w.donahue

Reputation: 10886

If you are talking about a C# windows forms application then what you want to use is the Observer pattern. See here for the pattern. Basically you want to have your controller register with the model via the observer pattern to be notified of any model changes that can cause the view to be obsolete. Then the controller can notify the view to re render the affected portion.

Upvotes: 1

twoflower
twoflower

Reputation: 6830

Ideally, you require some kind of push technology, since in your scenario the server initiates the update.

I would suggest two possible solutions:

  1. Polling (using AJAX): this basically means requesting the current count of unread messages periodically and thus in this case it is still browser who initiates the connection, not server. See the link for an example how to request the server and update your view with the retrieved data.
  2. If your server knows about the moment a new message arrives, I suggest using SignalR. It is a wrapper around several most popular push technologies (including fallback to long-polling if it finds out that it can't do better). I use it to my great satisfaction on our projects and it works like a charm. After you set up the basic infrastructure (see here), you can call directly your client's methods in from within MVC controller or you can call the server code directly from the client (in both cases client refers to some JavaScript you use in your view)

If you anticipate more and more information you will need to refresh in the future, I would definitely vote for SignalR as it will make your code much more maintainable.

Upvotes: 2

Related Questions