C# 使用AngularJS将表单数据发布到ASP.NET MVC应用程序中定义的ViewModel
我想使用AngularJS收集一些数据,并将其发布回我的ASP.NET WebAPI控制器 我将我的业务目标定义为这样,其目的是记录每年的总汽油消耗量以及每个月的消耗量:C# 使用AngularJS将表单数据发布到ASP.NET MVC应用程序中定义的ViewModel,c#,asp.net-mvc,angularjs,asp.net-web-api,C#,Asp.net Mvc,Angularjs,Asp.net Web Api,我想使用AngularJS收集一些数据,并将其发布回我的ASP.NET WebAPI控制器 我将我的业务目标定义为这样,其目的是记录每年的总汽油消耗量以及每个月的消耗量: public class PetrolViewModel { public double petrol_annual { get; set; } public int petrol_measure { get; set; } public List<Month> months { get;
public class PetrolViewModel
{
public double petrol_annual { get; set; }
public int petrol_measure { get; set; }
public List<Month> months { get; set; }
}
public class Month
{
public double jan { get; set; }
public double feb { get; set; }
}
当我提交表单数据并离开WebApi控制器接收匿名对象时,它似乎起作用,我得到表单数据:
但是,如果我更改此项并尝试传入我先前定义的ViewModel,则传入的对象为空:
我想充分利用ASP.NET的功能,自动映射匹配的名称,并向我提供一个填充的对象,然后在代码中处理该对象。我不想将匿名对象映射到ViewModel
因此,编程问题是:如何确保AngularJS对象与ViewModel匹配
在我一直在看的教程中,这似乎只适用于其他人,所以他们倾向于不太详细地介绍它
根据Fiddler的说法,下面是正在发送的JSON:
{"months":{"jan":"10","feb":"10","mar":"10","apr":"10","may":"10","jun":"10","jul":"10","aug":"10","sep":"5","oct":"5","nov":"20","dec":"10"},"petrol_annual":"120","petrol_measure":"1"}
我不确定为什么汽油年度或汽油计量不能正确绑定模型,但列表需要每月更新:
这是因为JSON中的月份是一个对象,而不是数组。它应该与服务器上的Month类匹配。Month类也应该包括所有月份的条目,但为了简洁起见,您可能刚刚在OP中输入了这些条目。下面的作品。很好。 代码:
你能举一个你正在发送的JSON的例子吗?当然。所以Fiddler告诉我它在发送:{月份:{1月10日,2月10日,3月10日,4月10日,5月10日,6月10日,7月10日,8月10日,9月5日,10月5日,11月20日,12月10日},汽油年度:120,汽油计量:1}出于某种神秘的原因,这解决了它,尽管我不知道为什么。我假设,因为汽油和汽油措施没有约束力,问题就在别处。我并没有想到错误地使用列表会导致整个事情失败。在调试过程中,我没有得到任何指示,但可能找错了地方。不管怎么说,我非常感谢你的回答,因为我会为此整夜挠头。对正如当今许多开发人员的典型情况一样,代码拼写错误严重,但运行良好。CatergorisViewModel,加上CatergoryName和CatergoryName,让我们了解这一点。我们可以用额外的0.5分钟来证明我们键入的内容。我支持上面的评论,这似乎是一个在这方面获得分数的微弱尝试
{"months":{"jan":"10","feb":"10","mar":"10","apr":"10","may":"10","jun":"10","jul":"10","aug":"10","sep":"5","oct":"5","nov":"20","dec":"10"},"petrol_annual":"120","petrol_measure":"1"}
public class PetrolViewModel
{
public double petrol_annual { get; set; }
public int petrol_measure { get; set; }
public Month months { get; set; }
}
public class CatergoriesViewModel
{
public string OrderSelected { get; set; }
public string CatergoryName { get; set; }
}
var data = { catergoryName: "TestCat", orderSelected: "true" };
$http.post("Category", data)
.then(function (response) {
$scope.test = response.data;
}, function (error) {
$scope.test = error;
});