Thursday, 15 September 2011

javascript - Custom action result return specific view in MVC C# -



javascript - Custom action result return specific view in MVC C# -

i have mvc application trying give user chance download zip of files,but unsuccesfully.let me explain further.

inside view(imageviewer.cshtml) have div class on click event when pressed phone call controller method(imageviewercontroller.getzipphotos) handles download of zip file.see below:

div class="text" onclick="getzipphotos()">download</div>

and javascript called this:

function getzipphotos() { $.ajax({ url: '@url.action("getzipphotos", "imageviewer",request.url.scheme)', type: 'post', contenttype: 'application/zip', error: function () { alert('there error!'+result); } }); }

now, within imageviewercontroller have next method:

[httppost] public actionresult getzipphotos() { zipresult newzipresult=new zipresult( server.mappath("~/file1.txt"), server.mappath("~/file2.txt") ); newzipresult.outputzipfilename = "photoszip.zip"; homecoming newzipresult; }

and declaration of zipresult custom action is:

public class zipresult:actionresult { private ienumerable<string> _filestozip; private string _outputzipfilename="zipfile.zip"; public zipresult(params string[] filestozip) { this._filestozip = filestozip; } public override void executeresult(controllercontext context) { using (zipfile onezipfile = new zipfile()) { onezipfile.addfiles(_filestozip); context.httpcontext.response.contenttype = "application/zip"; context.httpcontext.response.appendheader("content-disposition", "attachment; filename=" + _outputzipfilename); onezipfile.save(context.httpcontext.response.outputstream); } } }

the problem code ofcourse doesn't work because name of view called controller different actual method(getzipphotos).the view's name imageviewer.cshtml , controller's name imageviewercontroller. fas have understood, mvc framework uses code conventions, expects name of method same view.the problem view , method diferrent response never gets view. thought of creating new view has nil inside, phone call method , homecoming zip file.if possible solution, how can tell action result view send response?

no need utilize ajax file download. browser start download , maintain on same page. also, no need custom action result, can utilize fileresult. seek this:

public fileresult getzipphotos() { var filestozip = new list<string> { server.mappath("~/file1.txt"), server.mappath("~/file2.txt") }; var onezipfile = new zipfile(); onezipfile.addfiles(filestozip); homecoming file(onezipfile.tobytearray(), "application/zip", "photoszip.zip"); }

of course, you'll need figure out part onezipfile.tobytearray(), zipfile class has that.

javascript ajax asp.net-mvc-4 c#-4.0

No comments:

Post a Comment