Implementation code for message notification mechanism using ASP.NET MVC 4 Async Action+jQuery

  • 2020-05-26 08:11:59
  • OfStack

This two days in the use of Asp net MVC 4 development COMET message notification mechanism, in the back-end using asynchronous thread to subscribe to news, the client through AJAX long connection requests in MVC ACTION, such as: http: / / localhost event/imageSet, obtain ImageSet object changes of message (add, update, and delete the message).

1. Class IEventEntity for event messages < TEntity > The definition of a class


public interface IEntityEvent<TEntity>
    {
        // Changed entity class object 
        TEntity[] Entities
        {
            get;
        }
        // Operation type 
        EntityEventType Type
        {
            get;
        }
    }

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

2. EntityEventController class


[SessionState(SessionStateBehavior.ReadOnly)]
    public class EntityEventController : Controller
    {
        // Asynchronous acquisition pair ImageSet Change events for object operations Action . 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.Net Framework 4.5 makes the current asynchronous asp.net mvc async action(see: Using Asynchronous Methods in ASP. NET MVC 4 technical articles) technology, the method before async keyword can be used and Task object, according to the method for asynchronous method, run by the compiler to generate the required relevant asynchronous operation logic code, other methods must be used to await statements to wait for the end of an asynchronous operation await and Task < T > Combine to return Task completed Result

(2) if Controller is applied at the Controller level or Session is operated in Filter, Attribute [SessionState(SessionStateBehavior.ReadOnly)] needs to be added to Controller to indicate that Controller is read-only to Session, so that other operations will not be blocked, in order to avoid the situation that a long link will not lead to Session Block in other calls with es557en.

3. The code for the EntityEventSubscriber message subscriber is not specified here, but will be described in detail in a future article on "message subscription and publishing".

4.jQuery AJAX client code


$(document).ready(function () {
        var $hoverList = $("#imageSets").hoverList({title:" Photo gallery 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:  Handle entity class additions 
                            if(i == data.EntityEvent.Entities.length - 1){
                                getEvent();
                            }
                        });
                        return;
                    }
                    //Update
                    if(data.EntityEvent.Type == 1){
                        $.each(data.EntityEvent.Entities, function(i, entity){
                            //TODO:  Handles entity 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:  Handles entity class deletion 
                            if(i == data.EntityEvent.Entities.length - 1){
                                getEvent();
                            }
                        });
                    }
                }else{
                    $("#imageSets").hoverList("add", data);
                    getEvent();
                }
            });
        };
        getEvent();
    });

The main control in the code is getting the message once (with or without a message), and calling the getEvent() method once at the right time to loop through the message retrieval.


Related articles: