C# 如何将JSON数据发布到MVC4控制器?
我已将控制器设置为:C# 如何将JSON数据发布到MVC4控制器?,c#,asp.net-mvc,json,angularjs,C#,Asp.net Mvc,Json,Angularjs,我已将控制器设置为: [HttpGet] public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } [HttpPost] public ActionResult Contact(string json) { return Json(new { received=json }); } $scope.update = function (m
[HttpGet]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
public ActionResult Contact(string json)
{
return Json(new { received=json });
}
$scope.update = function (message) {
$http({
url: '/Contact',
method: "POST",
data: message
}).success(function (data) {
//$scope.master = angular.copy(message);
$scope.master = data;
}).error(function (data) {
$scope.master = {message: "failed"}
});
};
$scope.update = function (message) {
$http({
url: '/Contact',
method: "POST",
data: {json:message}
}).success(function (data) {
//$scope.master = angular.copy(message);
$scope.master = data;
}).error(function (data) {
$scope.master = {message: "failed"}
});
};
使用Angular.JS发送请求,如下所示:
[HttpGet]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
public ActionResult Contact(string json)
{
return Json(new { received=json });
}
$scope.update = function (message) {
$http({
url: '/Contact',
method: "POST",
data: message
}).success(function (data) {
//$scope.master = angular.copy(message);
$scope.master = data;
}).error(function (data) {
$scope.master = {message: "failed"}
});
};
$scope.update = function (message) {
$http({
url: '/Contact',
method: "POST",
data: {json:message}
}).success(function (data) {
//$scope.master = angular.copy(message);
$scope.master = data;
}).error(function (data) {
$scope.master = {message: "failed"}
});
};
但我现在得到的回应是:
{
"received": null
}
因此,我相信我的问题与我在控制器中定义的stringjson
参数有关接收JSON的正确方式是什么?
更新1:
我将$http请求更新为如下所示:
[HttpGet]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
public ActionResult Contact(string json)
{
return Json(new { received=json });
}
$scope.update = function (message) {
$http({
url: '/Contact',
method: "POST",
data: message
}).success(function (data) {
//$scope.master = angular.copy(message);
$scope.master = data;
}).error(function (data) {
$scope.master = {message: "failed"}
});
};
$scope.update = function (message) {
$http({
url: '/Contact',
method: "POST",
data: {json:message}
}).success(function (data) {
//$scope.master = angular.copy(message);
$scope.master = data;
}).error(function (data) {
$scope.master = {message: "failed"}
});
};
但是我还是得到了相同的结果。如下设置数据,否则MVC会希望参数名应该是
id
,而不是json
data: {json:JSON.stringify(message)}
仍在获取:
{“received”:null}
我还缺少什么吗?@anwyatt,需要使用JSON.Stringify。更新了我的回答为什么您不希望modelbinder绑定到强类型对象,而是提供原始JSON字符串?@ErikPhilips我不知道我会这么做。我选择了这条路线,以便可以使用Javascript实时发送数据。有更好的方法吗?如果你发布JSON的样子,我会在答案中给出一个例子。