AngularJS将数据作为键值对发布到asp.net页面

时间:2016-04-22 17:07:42

标签: javascript c# asp.net angularjs

我正在尝试将关键值对数据从角度应用程序发布到asp.net页面,但是我无法在asp.net页面上收到结果。

示例数据

 {fullName: "Vikas Bansal", userId: "1001387693259813", userimageurl: "http://graph.facebook.com/1001387693259813/picture?width=250&height=250"}

角色代码

    var postData = {
        fullName: $scope.name,
        userId: $scope.userId,
        userimageurl: $scope.userImage
    };

    var postUrl = 'http://localhost:41115/Index.aspx';

    $http({
        url: postUrl,
        method: "POST",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: postData
    }).then(function (responce) {
        console.log(responce);
    }, function (responce) {
        console.log(responce);
    });

Asp.net网页代码

protected void Page_Load(object sender, EventArgs e)
{
    var userId = Request.Form["userId"];    /// getting null
    var fullName = Request.Form["fullName"];    /// getting null
    var img = Request.Form["userimageurl"]; /// getting null
}

在asp.net页面中,所有变量都为null。

enter image description here

修改

在angularJs post request

中将内容类型更改为'Content-Type': 'application/json; charset=utf-8'

并使用var strJSON = (new StreamReader(Request.InputStream).ReadToEnd());我可以获得发布的json

但我仍然想知道是否有办法直接获得键值对?

喜欢这个var userId = Request.Form["userId"];

1 个答案:

答案 0 :(得分:2)

这是因为您的有效负载实际上是JSON,但您尝试将其作为FormData对象传递。

您需要制作一个FormData()对象。然后

(1)告诉AngularJs不要使用angular.identity函数对其进行序列化。

(2)Angular的 PUT POST 请求的默认标头为application/json,因此您也希望覆盖它。浏览器将Content-Type设置为multipart/form-data并填写正确的边界。

试试这个:

var postData = new FormData();
postData.append("fullName", $scope.name);
postData.append("userId", $scope.userId);
postData.append("userimageurl", $scope.userImage);

$http.post(postUrl, postData, {
    transformRequest: angular.identity,
    headers: { 'Content-Type': undefined }
}).then(function(data) {
    //success
}, function(error) {
    //error
});
相关问题