Use ASP. net mvc 4 Async Action + jQuery to implement the Message notification mechanism.

Source: Internet
Author: User

In the past two days, we have used Asp.net MVC 4 to develop the COMET Message notification mechanism. At the backend, we use an asynchronous thread to subscribe to messages. The client uses the AJAX persistent connection to request the ACTION in MVC, such as http: // localhost/event/imageSet indicates to obtain the change message (ADD, update, and delete messages) of the ImageSet object ).

1. Define the IEventEntity <TEntity> class of event messages

Copy codeThe Code is as follows: public interface IEntityEvent <TEntity>
{
// Changed object class
TEntity [] Entities
{
Get;
}

// Operation Type
EntityEventType Type
{
Get;
}
}

Public enum EntityEventType: int
{
Create = 0,
Update = 1,
Removed = 2
}

2. EntityEventController class

Copy codeThe Code is as follows: [SessionState (SessionStateBehavior. ReadOnly)]
Public class EntityEventController: Controller
{
// Obtain the change event Action for the ImageSet object operation asynchronously. millsecondsTimeout is the timeout time.
Public async Task <ActionResult> ImageSet (int millisecondsTimeout = 10000)
{
Return await this. EventAsync <ImageSetData> (millisecondsTimeout );
}

Private async Task <ActionResult> EventAsync <TEntity> (int millisecondsTimeout)
{
IEntityEvent <TEntity> entityEvent = await EntityEventSubcriber. Instance. WaitForEntityEvent <TEntity> (millisecondsTimeout );

Return this. Json (new
{
HasEvent = null! = EntityEvent,
EntityEvent = entityEvent

}, JsonRequestBehavior. AllowGet );
}
}

(1) It is used here. make Asynchronous asp.net mvc async action in Net Framework 4.5 (see Using Asynchronous Methods in ASP. net mvc 4 Technical Article). The async keyword before the method can be used with the Task object to indicate that the method is an Asynchronous Method, the logic code of the asynchronous operation required by the compiler to generate the runtime. In addition, the await statement must be used in the method to wait for the end of an asynchronous operation, await and Task <T> are combined to return the Result of Task completion.

(2) If the Controller-level application or Filter has performed Session operations, in order to avoid the situation where the Session Block is not transferred to the same Session during other calls during long links, you need to add [SessionState (SessionStateBehavior. readOnly)] Attribute to indicate that the current Controller is a read-only operation on the Session, so that other operations will not be blocked.

3. The code of the EntityEventSubscriber message subscriber will not be specifically written here. It will be described in detail in the "message subscription and publishing" article.

4. jQuery AJAX client code

Copy codeThe Code is as follows: $ (document). ready (function (){

Var $ hoverList = $ ("# imageSets"). hoverList ({title: "image set list", selectedIndex: 1 });

Var getEvent = function (){

Var getPattern = "/EasyshirtBackend/imageSet/0 ";

$. GetJSON ("/EasyshirtBackend/event/imageSet/100000", function (data ){

If (data. HasEvent ){

// Create
If (data. EntityEvent. Type = 0 ){

$. Each (data. EntityEvent. Entities, function (I, entity ){

// TODO: New Entity class Processing

If (I = data. EntityEvent. Entities. length-1 ){

GetEvent ();
}
});

Return;
}

// Update
If (data. EntityEvent. Type = 1 ){

$. Each (data. EntityEvent. Entities, function (I, entity ){

// TODO: Process object class updates

If (I = data. EntityEvent. Entities. length-1 ){

GetEvent ();
}
});

Return;
}

// Delete
If (data. EntityEvent. Type = 2 ){

$. Each (data. EntityEvent. Entities, function (I, entity ){

// TODO: Process object class Deletion

If (I = data. EntityEvent. Entities. length-1 ){

GetEvent ();
}
});
}

} Else {

$ ("# ImageSets"). hoverList ("add", data );
GetEvent ();
}
});
};

GetEvent ();
});

In the code, you need to control the cycle in which messages are obtained at an appropriate time (whether there is a message or no message), and call the getEvent () method at an appropriate time.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.