Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

How to pass data from angularjs to asp net mvc controller method?

Tried the technique from AngularJs $http.post() does not send data:

<!doctype html>
<html ng-app="targetApp">
<head>
<title>Targets</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/b..">
</head>
<body ng-controller="targetController">
<div class="page-header">
<h1> Список дел на сегодня</h1>
</div>
<div class="panel">
<div class="form-inline">
<div class="form-group">
<div class="col-md-8">
<input class="form-control" ng-model="target" placeholder="Цель" />
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<input type="number" class="form-control" ng-model="priority" placeholder="Приоритет" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-4">
<button class="btn btn-default" ng-click="addItem(target, priority)">Добавить</button>
</div>
<div class="col-md-offset-2 col-md-4">
<button class="btn btn-default" ng-click="save('123')">Сохранить</button>
</div>
</div>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Цель</th>
<th>Приоритет</th>
<th>Сделано</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in list.items">
<td>{{item.target}}</td>
<td>{{item.priority}}</td>
<td><input type="checkbox" ng-model="item.done" /></td>
</tr>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1.."></script>
<script>
var model = {
items: [
{ target: "Попробовать angular.js", priority: 1, done: false },
{ target: "Съесть бизнес-ланч", priority: 2, done: true }
]
};
var targetApp = angular.module("targetApp", []);
targetApp.controller("targetController", function ($scope, $http) {
$scope.list = model;
$scope.addItem = function (target, priority) {
$scope.list.items.push({ target: target, priority: priority, done: false });
};

// Use x-www-form-urlencoded Content-Type
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$scope.save = function (target) {
$http.post('/DayActivity/testPost', $scope.list.items[0]).success(function (answ) {
});
};

/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* Ольга Штамм {Object} obj
* Артём Зайцев {String}
*/
var param = function (obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
for (name in obj) {
value = obj[name];
if (value instanceof Array) {
for (i = 0; i < value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if (value instanceof Object) {
for (subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}
else if (value !== undefined && value !== null)
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
return query.length ? query.substr(0, query.length - 1) : query;
};

// Override $http service's default transformRequest
$http.defaults.transformRequest = [function (data) {
return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
}];
});
</script>
</body>
</html>

And the code of the mvc controller:

public class DayActivityController : Controller
{
[HttpPost]
public ActionResult testPost(JsonResult j)
{
return null;
}
}

Unfortunately, the data JsonResult.Data is null. How to pass the data from angularks to the asp net mvc controller method?

share|improve this question
2  
Please format your post and code. This is really hard to understand. – Qi Tang Jul 31 '15 at 15:32
    
can you please try object instead of JsonResult? – Chander .k Jul 31 '15 at 15:33
    
Sorry guys. Tried to format. Hope this time the code is better to read. – truel Jul 31 '15 at 15:38

Here is my ApiController version. Maybe it can help.

transformRequest is the main hint to chase

    logError: function (action, context, type, message) {
        var resourceUri = 'log/dosomething/';
        var jsonObject = { "Action": action,"Message": message,"Context":context };

        var logQuery = $resource(resourceUri, {} , {
            save: {
                method: 'POST',
                transformRequest: function (data, headersGetter) {
                    var result = JSON.stringify(jsonObject);
                    return result;
                }
            }
        }).save();
    }



public class LogController :    ApiController

    [HttpPost]
    [ActionName("DoSomething")]
    public void DoSomething([FromBody]MyObject myObj)
    {

    }


public class MyObject
{
    public string Action { get; set; }

    public string Message { get; set; }

    public string Context { get; set; }


}

}

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.