-1

I am displaying the results on an angular js interface through Web API calls in MVC.

But then, based on some selections, I would need to pass some parameters and call the following MVC Controller method that downloads a file.

public ActionResult Downloadfile(string selectedIds, string selecteddefs, DateTime date)
{
    // do some stuff here
    var file = new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
    {
        FileDownloadName = string.Format("download_{0}.docx", DateTime.Now.ToString("ddMMyyyyHHmmss"))
    };

    return file;
}

This is a normal MVC Controller which does not inherit from ApiController.If I make the http post like below in the angular function, it's not downloading file thought it hits the controller method. This is probably, it's returning json data rather than downloading a file.And I should not do this I think, since the Controller is a normal MVC one, does not inherit ApiController.

$http.post('/ControllerName/MethodName?selectedIds=' + selectedIds + '&selecteddefs=' + selecteddefs + '&date=' + date, {});

So I tried the normal jquery like below.

$.ajax({

    url: "/ControllerName/ActionName",
    data: { 'selectedIds': selectedIds.toString(), 'selecteddefs': selecteddefs.toString(), 'date': date },
    type: "POST"

});

The above hits the Controller method and does all the work, but then again not able to download any file.

How can I call a normal MVC Controller Action method where the functionality of the method is just to download a file. There is no problem with Action method. Could anyone please help.

I have tried the following.But it does not hit the controller Action.

   $http({
            method: 'POST',
            url: '/Controller/ActionName',
            data: $httpParamSerializerJQLike({ nodeIds: JSON.stringify(nodes.toString()), glossaryTermIds: JSON.stringify(glossaryterms.toString()), date: JSON.stringify(date.toString()) }),
            headers: { 'Content-Type' : 'application/x-www-form-urlencoded'}
        })
        .then(function (result){

        }, function (result) {
        });
Community
  • 1
  • 1
Rama
  • 73
  • 1
  • 4
  • 14
  • Possible duplicate of [Download file of any type in Asp.Net MVC using FileResult?](http://stackoverflow.com/questions/3604562/download-file-of-any-type-in-asp-net-mvc-using-fileresult) – BentOnCoding Dec 07 '15 at 21:19
  • Your question and title doesn't match...It sounds like the parameters are being sent from the view to the controller? Does selectedIds have a value if you run in debug? – Anonymous Dec 07 '15 at 21:21
  • Possible duplicate of [Handle file download from ajax post](http://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post) – Rhumborl Dec 07 '15 at 21:28

4 Answers4

3

No need for complicated Posts, use this the angular window object instead of the location object:

$window.location.assign("/ControllerName/ActionName");
Sagi
  • 981
  • 11
  • 15
0

Use $resource service of angularJS to create http requests

$resource('host/ControllerName/ActionName').get();

you can pass parameters as well.

Follow this link

Ashutosh Singh
  • 609
  • 6
  • 21
0

It's quite common mistake when using AngularJs with C#. Wasted some of my time a while ago.

You have to use $httpParamSerializerJQLike as a dependency and a sample request should look like:

$http({
    method: 'POST',
    url: 'ControllerName/MethodName',
    data: $httpParamSerializerJQLike({ blah: JSON.stringify(data)}),
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function (result) {
    // Success
}, function (result) {
    // Error
});

AngularJs is using 'application/json' as Content-Type by default.

Fayyaz Naqvi
  • 695
  • 7
  • 19
Chris Hermut
  • 1,708
  • 3
  • 17
  • 32
  • I have tried as you mentioned above and have updated the post. But it does not hit the controller Action. – Rama Dec 08 '15 at 10:13
  • Try removing first / from "url: '/Controller/ActionName'". Also have a look if you're sending a correct request (ex. using Fiddler). – Chris Hermut Dec 08 '15 at 10:15
  • No luck. I just want to hit the MVC Controller and should carry on downloading a file. Nothing to be returned to the interface – Rama Dec 08 '15 at 10:23
  • So you are unable to hit a breakpoint on your method when firing up your 'POST' request? – Chris Hermut Dec 08 '15 at 10:27
  • Is your request matching method signature? Do you get any network errors? Does it have [HttpPost] decorator? Maybe you're just hitting another method? – Chris Hermut Dec 08 '15 at 11:23
  • Also why are you using .toString() in JSON.stringify? – Chris Hermut Dec 08 '15 at 11:24
0

It's quite simple to invoke ASP.Net MVC Controller action method using AngularJS as follows:

In Javascript I wrote:

var app = angular.module('MyApp', []);   
angular.module('MyApp', [])  
            .controller('MyController', ['$scope', '$http', function ($scope,  
  $http) {  
                $scope.search = function () {  
                    $http({   
                        method: "GET",   
                        url: "/home/GetData"   
                    }).then(function mySuccess(response) {   
                        $scope.name = response.data;   
                    }, function myError(response) {   
                        $scope.name = response.statusText;   
                    });   
                }   
            }]);   

In HTML part, I wrote:

<button ng-click="search()">Get Data</button>   

In Controller Action, I wrote:

return Json("You caught AngularJS", JsonRequestBehavior.AllowGet);