javascript - 具有.net核心模型的AngularJS未绑定(bind)

标签 javascript angularjs asp.net-core asp.net-core-mvc

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

我有以下 Angular 片段:

//The data I need to send.
$scope.PersonalInfo = {
    firstName: '',
    lastName: '',
    companyName: '',
    email: '',
    password: '',
    confirmPassword: '',
    imageLink: ''
};

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

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

最后是应该发送它的方法:

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

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

Model not being bound...

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

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

最佳答案

您需要在 post 调用中提及 [FromBody] 属性。像这样,

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

        return Json(new { Data = profile });
    }

应该可以了。

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

详细信息:https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

关于javascript - 具有.net核心模型的AngularJS未绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43742830/

相关文章:

javascript - 如何读取拦截器内的配置参数?

angularjs - 在同一元素上嵌套 ng-repeat,而不展平原始数据源

asp.net-mvc - 如何在MVC6或AspNet Core或IdentityCore中更改PasswordValidator

c# - 在 .net5/vNext/MVC6 中添加新的路由约束

javascript - 在 href 属性中插入 javascript 变量

javascript - 当一个对象有额外的键时,如何使用 Lodash 比较 JSON 对象中的键和值?

javascript - AngularJS:如何有条件地应用 View 动画?

javascript - 使用 window.scrollY 进行 Canvas 计算会导致问题

javascript - JQuery DataTables 和 ColVis 插件错误 "Cannot read property ' sWidth' of undefined"

asp.net-core - Entity Framework 核心脚手架对方法的访问失败