【问题标题】:AngularJS with .net core model not binding具有.net核心模型的AngularJS未绑定
【发布时间】:2017-09-30 06:27:21
【问题描述】:

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

我有以下角度 sn-p:

//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 发送,或发送范围对象),当请求到达控制器时,我都会得到以下结果:

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

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

【问题讨论】:

  • 发送前无需对 JS 对象进行字符串化(由$http 自动完成)。你试过没有字符串化吗?
  • 是的,我做了,不管有没有它都没有绑定。
  • 在 PascalCase 中创建 C# UserProfileModel ... UserId、FirstName 等...这可能与 JSON 序列化程序设置有关。
  • 你能把userId: '' 加到PersonalInfo 看看是否可行,它可能正在寻找所有属性。
  • 你知道如何使用谷歌浏览器的网络流量工具来检查请求/响应吗?

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


【解决方案1】:

您需要在通话后提及 [FromBody] 属性。像这样,

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

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

应该这样做。

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

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

【讨论】:

  • 太好了,效果很好。如果我可以问。为什么现在需要添加注释才能做到这一点?它以前默认接受来自请求正文的数据。
  • 嗨 Muqeet Khan,我也尝试使用 FromBody,但没有在我们的模型中绑定数据,所以任何其他方式来绑定数据
  • 嗨,Durga Siva,.Net Core 现在要求您的请求发送 json 的内容类型,否则也不会接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-28
  • 2021-12-02
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
相关资源
最近更新 更多