简体   繁体   English

如何从angular js调用MVC Controller Action方法

[英]how to call MVC Controller Action method from angular js

I am displaying the results on an angular js interface through Web API calls in MVC. 我正在通过MVC中的Web API调用在有角js界面上显示结果。

But then, based on some selections, I would need to pass some parameters and call the following MVC Controller method that downloads a file. 但是,然后,基于一些选择,我需要传递一些参数,并调用下面的MVC Controller方法来下载文件。

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. 这是一个普通的MVC控制器,它不是从ApiController继承的。 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. 这可能是因为它返回的是json数据而不是下载文件。我认为我不应该这样做,因为Controller是一种普通的MVC,它不会继承ApiController。

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

So I tried the normal jquery like below. 所以我尝试了如下所示的普通jquery。

$.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. 上面的代码命中了Controller方法并完成了所有工作,但随后又无法下载任何文件。

How can I call a normal MVC Controller Action method where the functionality of the method is just to download a file. 如何调用普通的MVC Controller Action方法,该方法的功能仅仅是下载文件。 There is no problem with Action method. 动作方法没有问题。 Could anyone please help. 谁能帮忙。

I have tried the following.But it does not hit the controller Action. 我尝试了以下方法。但是它没有击中控制器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) {
        });

无需复杂的帖子,请使用此角度窗口对象代替位置对象:

$window.location.assign("/ControllerName/ActionName");

Use $resource service of angularJS to create http requests 使用angularJS的$ resource服务创建http请求

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

you can pass parameters as well. 您也可以传递参数。

Follow this link 点击此链接

It's quite common mistake when using AngularJs with C#. 在C#中使用AngularJs时,这是一个很常见的错误。 Wasted some of my time a while ago. 前一段时间浪费了我一些时间。

You have to use $httpParamSerializerJQLike as a dependency and a sample request should look like: 您必须使用$ httpParamSerializerJQLike作为依赖项,并且示例请求应类似于:

$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. AngularJs默认使用'application / json'作为Content-Type。

It's quite simple to invoke ASP.Net MVC Controller action method using AngularJS as follows: 使用AngularJS调用ASP.Net MVC Controller操作方法非常简单,如下所示:

In Javascript I wrote: 在Javascript中,我写道:

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: 在HTML部分,我写道:

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

In Controller Action, I wrote: 在Controller Action中,我写道:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM