【问题标题】:ASP.NET MVC 4 FormCollection is Empty using Angularjs $Http.post使用 Angularjs $Http.post 的 ASP.NET MVC 4 FormCollection 是空的
【发布时间】:2014-09-11 12:52:33
【问题描述】:

我正在使用 Angularjs (1.2.20)Microsoft ASP.Net MVC 4 提交表单帖子:

public ActionResult Save2(FormCollection customer)
{
   //TODO: Do some stuffs...
   return new HttpStatusCodeResult(HttpStatusCode.OK);
}

但是,FormCollection 是空的。我知道数据正在发送,因为如果我将其更改为下面的代码(使用强类型CustomerVm),它会按预期工作。

public ActionResult Save1(CustomerVm customer)
{
   //TODO: Do some stuffs...
   return new HttpStatusCodeResult(HttpStatusCode.OK);
}

我正在使用FormCollection,以便我可以在数据中添加 ASP.Net 防伪令牌(而不是标题)。下面是我的自定义 javascript 代码。您还可以找到整个代码 (Visual Studio) here

【问题讨论】:

    标签: javascript asp.net asp.net-mvc angularjs asp.net-mvc-4


    【解决方案1】:

    您需要发送内容类型为application/x-www-form-urlencoded 的请求,并对请求正文进行编码。这是一个好的开始,但它以 JSON 格式发送数据。

    var data = JSON.stringify(customer);
    
    // FormCollection
    $http({
        method: 'POST',
        url: '/Home/Save2',
        //dataType: 'json',
        contentType: 'application/x-www-form-urlencoded; charset-UTF-8',
        //contentType: 'application/json; charset-UTF-8',
        data: data
    });
    

    将对象转换为 URL 编码形式实际上非常复杂。值得庆幸的是,Ben Nadel 已经通过请求转换器创建了一个transformRequestAsFormPost service to do this。您可以通过添加他的代码并将此更改更改为您的代码来尝试一下...

    myApp.factory('customerSvc', function ($http, transformRequestAsFormPost) {
        return {
            // ...
            save2: function (customer, antiForgeryToken) {
                $http({
                    method: 'POST',
                    url: '/Home/Save2',
                    transformRequest: transformRequestAsFormPost,
                    data: data
                });
            }
        };
    });
    

    【讨论】:

      猜你喜欢
      • 2013-10-15
      • 1970-01-01
      • 2015-02-12
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      相关资源
      最近更新 更多