在ASP.Net Core中发布json时,MVC模型为null [英] MVC model is null when posting json in ASP.Net Core

查看:83
本文介绍了在ASP.Net Core中发布json时,MVC模型为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有相关代码:

//JSON data
var dataType = 'application/json; charset=utf-8';
var data = {
    FirstName: 'Andrew',
    LastName: 'Lock',
    Age: 31
}

console.log('Submitting form...');
$.ajax({
    type: 'POST',
    url: '/Diary/Save',
    dataType: 'json',
    contentType: dataType,
    data: data,
    success: function (result) {
        console.log('Data received: ');
        console.log(result);
    }
});


[HttpPost]
public IActionResult Save([FromBody] Person person)
{
    return Json(person);
}



public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

Save方法中的"person"始终为null.这应该可以工作...感觉好像是设置问题吗?我是否需要在此处进行更改:

"person" in the Save method is always null. This should work...it feels perhaps like a settings issue? Do I need to make changes here:

 services.AddMvc(options =>
        {
        });

推荐答案

您需要对发送到服务器的数据进行字符串化,以将其转换为JSON,因为这是您指示的内容类型标头:

You need to stringify the data that you are sending to the server to convert it to JSON because that's the content type header you indicated:

data: JSON.stringify(data)

这篇关于在ASP.Net Core中发布json时,MVC模型为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆