【问题标题】:JSON object model not utilizing JsonProperty namesJSON 对象模型不使用 JsonProperty 名称
【发布时间】:2021-12-22 12:23:58
【问题描述】:

如何让组件工厂在对 Razor 操作结果的 AJAX 请求中绑定和解析 JSON 属性属性名称? 现在,我有一个解决方法,我只发送 JSON 字符串并在服务器端反序列化它,但认为必须有一种方法可以让操作执行此操作。

例如,我有以下模型:

public class ExampleClass 
{
    [JsonProperty("@first-name")]
    public string FirstName { get; set; }

    [JsonProperty("@last-name")]
    public string LastName { get; set; }
}

然后我尝试使用以下脚本发送我的模型(请注意,我已经删除了剃刀视图模型绑定的双“@@”以避免混淆)。这是“渲染”的脚本:

var model = {
        "@first-name": "test",
        "@last-name": "test"
    };

    $.ajax({
        url: '/Dashboard?handler=test',
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(model),
        beforeSend: function (xhr) {
            xhr.setRequestHeader("RequestVerificationToken", $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        success: function (result) {

        },
        error: function (result) {
        }
    });

在我的处理程序上,我得到一个空对象(模型值为空)

public IActionResult OnPostTest([FromBody] ExampleClass model)

如果我将模型更改为以下,一切正常:

var model = {
        "FirstName": "test",
        "LastName": "test"
    };

我可以看到对象正在正确传递

【问题讨论】:

    标签: json ajax .net-core razor-pages


    【解决方案1】:

    我犯了一个愚蠢的错误...我使用的是 Newtonsoft.Json 库属性属性绑定 (JsonProperty),而不是 System.Text.Json.Serialization 中的操作 (JsonPropertyName) 使用的序列化器工厂...非常愚蠢的时刻。在我删除 Newtonsoft 导入并看到我的课程现在出现错误时意识到,

    现在工作...

    public class ExampleClass 
    {
        [JsonPropertyName("@first-name")]
        public int FirstName { get; set; }
    
        [JsonPropertyName("@last-name")]
        public int LastName { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-20
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多