chobo2
chobo2

Reputation: 85715

How to render response stream with jquery?

I have this

    MemoryStream export = new MemoryStream();
    iCalendarSerializer serializer = new iCalendarSerializer(iCal);
    serializer.Serialize(export,System.Text.Encoding.UTF8);
    return export;

so I am using the C# DDay.iCal library for exporting my calendars. Serialize takes in a "stream" so I passed it a memory stream.

I now have a generic handler that calls the method that contains the above code.

 public class CalendarHandler : IHttpHandler
    {
        private Calendar service;
        private Membership membershipS;

        public void ProcessRequest(HttpContext context)
        {
            service = new Calendar ();
            membershipS = new Membership (null);
            string userName = context.User.Identity.Name;
            Guid userId = membershipS.GetUsersId(userName);

            context.Response.ContentType = "text/calendar";
            // calls the export calendar(the code that showed above that uses dDay ical.
            var t = service.ExportCalendar(userId);

            t.WriteTo(context.Response.OutputStream);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

So now I wrote the icalendar to the Outputstream. Now I have a jquery post that goes to this method and now I am not sure how to take the OutputStream result that the jquery post will get and make it popup with a save dialog box.

$('#ExportCalendar').click(function(e)
{
    $.post('../Models/CalendarHandler.ashx', null, function(r)
    {

    });

    return false;
});

Upvotes: 1

Views: 2430

Answers (2)

user24359
user24359

Reputation:

You can't make a file dialog popup via ajax. However, you can do:

document.location = yourRequestUrl

and that will generate a dialog. If you really need it to be a post, use

$(this).parent("form").submit()

as your click handler.

Be sure to set the context.Response.ContentType to "text/ical". That tells the browser what to do with the response.

Upvotes: 0

Eilon
Eilon

Reputation: 25704

I don't think that an AJAX post can cause a file save dialog to show up. This is because AJAX posts are for programmatically making web requests and happen behind the scenes (that is, without the user's knowledge).

Try changing the link to be a regular (non-AJAX) link, such as:

<a href="CalendarHandler.ashx">Save Calendar</a>

You'll also want to set the content disposition header to get the nice file save dialog. See this link for more info:

http://www.hanselman.com/blog/TheContentDispositionSagaControllingTheSuggestedFileNameInTheBrowsersSaveAsDialog.aspx

Upvotes: 1

Related Questions