Javascript AngularJS:如何通过$http post将JS对象发送到c#controller?
以下是我向服务器发送http post请求的AngularJS控制器代码:Javascript AngularJS:如何通过$http post将JS对象发送到c#controller?,javascript,c#,angularjs,http,post,Javascript,C#,Angularjs,Http,Post,以下是我向服务器发送http post请求的AngularJS控制器代码: 'use strict'; var input = {title: "", note:""}; notes.controller('inputController', function inputController($scope, $http) { $scope.cancleInput = function () { //not yet implemented }
'use strict';
var input = {title: "", note:""};
notes.controller('inputController', function inputController($scope, $http) {
$scope.cancleInput = function () {
//not yet implemented
}
$scope.saveInput = function () {
input.title = $scope.title;
input.note = $scope.note;
$http.post("/saveData/writeData", input);
}
})
这是我在C#控制器中的代码:
public class saveDataController : Controller
{
public static void writeData(input input)
{
var jsonString = new JavaScriptSerializer().Serialize(input);
//other code
}
}
http post调用无法识别C#方法。
我很确定我的URL是错误的,或者我缺少任何C#属性
我遇到以下错误:
POST 500(内部服务器错误)
C#方法没有达到断点,因此post请求永远不会调用它。我认为您应该通过从C#控制器中的输入流数据获取post数据来进行检查。您将收到500个错误,因为$http将发布包含“application/json”内容类型的ajax请求,该内容类型无法通过request.Form集合访问。试着改变公众形象
public static void writeData(input input)
到
并使用Request.InputStream获取数据
var Res = new StreamReader(Request.InputStream);
尝试通过继承ApicController创建API控制器,并使用HttpPost谓词修饰方法,如下所示-
public class saveDataController : ApiController
{
[HttpPost]
public static void writeData(input input)
{
var jsonString = new JavaScriptSerializer().Serialize(input);
//other code
}
}
以下是我所做的工作: 我在WebApiConfig文件中添加了自定义Api配置
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{Action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
然后,我根据新的Api配置修改了HTTPPOST URL
$http.post("/api/saveData/writeData", input);
然后我让C#控制器从ApiController继承。
我做的最后一个更改是,我在C#方法中添加了[httppost]属性,并删除了static关键字。
(我不理解为什么在方法定义中使用“static”会使HTTP POST无法检测该方法。)
您得到的是哪个js错误?在此处给出angular js控制器声明代码。@ranakrunal9我已将信息添加到您要求的post中。它未达到断点,因此post请求从未调用writeData()函数。我相信我发送邮件请求的方式有问题@拉纳克鲁纳尔9
$http.post("/api/saveData/writeData", input);
public class saveDataController : ApiController
{
[HttpPost]
public void writeData(input input)
{
//bunch of code
}
}