Question

I understand that TempData is designed to work only between a single page request. But I think have a situation I think breaks the intended functionality.

I use Controllers in preference to Handlers for delivering images. I don't now if that is best practice, but it works very well for me. The problem though, is that each call to one of the image Actions obviously uses up a TempData credit.

Is there a way in MVC to say "This Controller/Action is out of the scope of normal page requests" and therefore either persist the TempData or remove itself from the TempData life cycle completely?

Rich

Was it helpful?

Solution

My solution has been to create an Attribute that persists the TempData across page requests. My initial reaction to this is "yuck", but I want to effectively exclude any controllers decorated with the Attribute from the TempData lifecycle.

using System.Web.Mvc;

namespace K3R.Web.Mvc.Filters {
    public sealed class PersistTempDataAttribute : ActionFilterAttribute {
        public PersistTempDataAttribute() { }

        public override void OnActionExecuting(ActionExecutingContext filterContext) {
            var tempData = filterContext.Controller.TempData;
            if (tempData == null || tempData.Count == 0)
                return;

            string[] keys = new string[tempData.Keys.Count];
            tempData.Keys.CopyTo(keys, 0);
            foreach (var key in keys)
                tempData[key] = tempData[key];
        }
    }
}

Any feedback on a better solution would be appreciated.

Rich

OTHER TIPS

I'm not sure of the exact answer to this as I'm pretty new to MVC myself. However, I have heard of people having trouble with AJAX requests killing off the TempData before they wanted it to as well.

I guess you could implement your own Session based system to store this information?

I'm sure someone else will have a more complete answer for you soon, though!

I do not completely understand your way of doing it and why but I would rather go with handlers. Or if you stick to controller actions, I can say that this worked for me fine without any issues for delivering images on-the-fly and I used FileContentResult in my controller actions.

Like this:

        return File(imageBytes, imageType);

You get the bytes out of datastore or somewhere..

hope it helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top