AngularJS与.net核心模型没有绑定

Car*_*dez 1 javascript angularjs asp.net-core-mvc asp.net-core

所以我一直在学习一些.net核心,我正在用它构建一个API.通常我会使用角度并在那里发送请求.

我有以下角度片段:

//The data I need to send.
$scope.PersonalInfo = {
    firstName: '',
    lastName: '',
    companyName: '',
    email: '',
    password: '',
    confirmPassword: '',
    imageLink: ''
};
Run Code Online (Sandbox Code Playgroud)

然后是相同数据的后端模型:

public class UserProfileModel
{

    public string userID { get; set; }

    public string firstName { get; set; }

    public string lastName { get; set; }

    public string companyName { get; set; }

    public string email { get; set; }

    public string password { get; set; }

    public string confirmPassword { get; set; }

    public string imageLink { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

最后应该发送它的方法:

$scope.UpdateProfile = function () {

    var profile = JSON.stringify($scope.PersonalInfo);

    $http.post('/api/Profile/Users', profile).then(function (response) {
        debugger;
        $log.log(profile);
        $log.log(response);
    });
};
Run Code Online (Sandbox Code Playgroud)

无论我做了多少更改,(将数据作为字符串化的JSON发送,或发送范围对象),当请求到达控制器时,我最终得到:

模型没有受到约束......

$ scope.PersonalInfo在发送请求之前充满了数据.

非常感谢任何帮助.提前致谢.

Muq*_*han 5

您需要在帖子中提及[FromBody]属性.像那样,

    [HttpPost]
    [Route("api/bar/users")]
    public IActionResult Users([FromBody]UserProfileViewModel profile)
    {

        return Json(new { Data = profile });
    }
Run Code Online (Sandbox Code Playgroud)

应该这样做.

使用该FromBody属性的必要性使框架可以使用正确input formatter的模型绑定.例如,使用内容类型application/json的默认格式化程序是基于Json.Net的JSON格式化程序

有关详细信息,访问:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding