Home > Development > Adding Behaviors to ActionResults

Adding Behaviors to ActionResults


One problem you have with MVC is that you often need to tweak action response and add additional functionally to them. One solution is to sub class. The issues here you end up with a mess of classes and a deep inheritance tree. One solution decorator pattern.

public class ActionResultDecorator : ActionResult
    {

        protected ActionResult WrappedAction { get; private set; }

        public ActionResultDecorator(ActionResult wrappedActionResult)
        {
            WrappedAction = wrappedActionResult;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            WrappedAction.ExecuteResult(context);
        }
    }

     public class MimeTypeActionResultDecorator : ActionResultDecorator
    {

        public string MimeType { get; set; }

        public MimeTypeActionResultDecorator(ActionResult wrappedActionResult)
            : base(wrappedActionResult)
        {
        }

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = MimeType;
            base.ExecuteResult(context);
        }
    }


Simple solution like a Russian doll.

Blair

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: