繁体   English   中英

使用AngularJS将表单数据发布到ASP.NET MVC应用程序中定义的ViewModel

[英]Using AngularJS to post form data to a ViewModel that is defined within ASP.NET MVC application

我想使用AngularJS收集一些数据并将其发布回我的ASP.NET WebAPI控制器。

我已经定义了我的业务对象(其目的只是记录年度汽油总消耗量以及每月的消耗量):

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; }
}

在我的Angular代码中,我有:

var app = angular.module('petrol', []);

app.controller('PetrolController', function ($scope, $http) {

$scope.petrol = {};

$scope.petrol.months = {};

$scope.sendForm = function() {
    $http({
        method: 'Post',
        url: 'api/values',
        data: $scope.petrol
    }).success(function (data, status, headers, config) {
        console.log(data);
        console.log(status);
        console.log(headers);
    }).error(function (data, status, headers, config) {
        console.log(data);
        console.log(status);
        console.log(headers);
    });
};

});

当我提交表单数据并离开WebApi控制器以接收匿名对象时,它似乎可以工作,并且我得到了表单数据:

传入对象类型时的调试信息

但是,如果我更改此设置并尝试传入之前定义的ViewModel,则会传入一个空对象:

尝试作为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"}

我不确定为什么petrol_annualpetrol_measure没有正确绑定模型,但是List<Month>必须改为Month

public class PetrolViewModel
{
    public double petrol_annual { get; set; }
    public int petrol_measure { get; set; }

    public Month months { get; set; }
}

这是因为JSON中的months是对象,而不是数组。 它应该与服务器上的Month类匹配。 Month班也应包括所有月的条目,但为简洁起见,您可能已省略了这些条目。

下面的作品。 很好。 码:

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;
 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM