【问题标题】:Enum value doesn't show EnumMember value on razor page ASP.NET Core 3.1枚举值在剃须刀页面 ASP.NET Core 3.1 上不显示 EnumMember 值
【发布时间】:2020-10-18 14:06:50
【问题描述】:

我有一个 Razor 页面,并在该页面上显示 JavaScript 数据表中的数据。我试图将枚举值显示为字符串,但我的枚举值没有得到正确的字符串表示形式。

Startup.cs

services.AddRazorPages().AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.IgnoreNullValues = true;
        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
    });

枚举.cs

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Operation
{
    [EnumMember(Value = "None")]
    None,
    [EnumMember(Value = "Send e-mail")]
    SendEmail,
    [EnumMember(Value = "Download file")]
    DownloadFile
}

Result.cs

public class Result
    {
        public int Id { get; set; }

        public DateTime StartDate { get; set; }

        public DateTime EndDate { get; set; }

        [Column(TypeName = "smallint")]
        [JsonConverter(typeof(JsonStringEnumConverter))]
        public Operation Operation { get; set; }

        public bool Success { get; set; }
    }

结果页

public IActionResult OnPost()
{
     var resultData = _dbContext.Results.ToList();

     var jsonData = new {recordsTotal = resultData.Count(), data = resultData
};

     return new JsonResult(jsonData);
}

结果视图 这里只是 JS 数据表的脚本

<script>
    $(document).ready(function () {
        $('#resultDatatable').dataTable({
            "processing": true,
            "serverSide": true,
            "filter": true,
            "ajax": {
                url: "/Result",
                type: 'POST',
                headers: { 'RequestVerificationToken': $('@Html.AntiForgeryToken()').val() }
            },
            "columns": [
                { "data": "id", "name": "Id", "autoWidth": true, "visible": false},
                {
                    "data": "startDate", "name": "Start date", "autoWidth": true, "render": function (d) {
                        return moment(d).format("YYYY/MM/DD");}
                },
                {
                    "data": "endDate", "name": "End date", "autoWidth": true, "render": function(d) {
                        return moment(d).format("YYYY/MM/DD");}
                },
                { "data": "operation", "name": "Operation", "autoWidth": true },
                { "data": "success", "name": "Success", "autoWidth": true }
            ]
        });
    });
</script>

当我调用它时,我会从 EnumMember 值中得到正确的枚举表示:

var test = JsonConvert.SerializeObject(resultData); //SendEmail -> "Send e-mail"

但是,当我:

return new JsonResult(resultData);      //SendEmail -> "SendEMail"

我尝试了这个解决方案ASP.NET MVC Core API Serialize Enums to String,但没有得到预期的结果。

【问题讨论】:

    标签: c# asp.net-core enums datatables razor-pages


    【解决方案1】:

    经过 3 个小时的挣扎,我发现:

    System.Text.Json.Serialization.JsonStringEnumConverter 支持将枚举序列化为字符串,但未实现通过属性重命名。

    所以我使用了这个链接中接受的答案,我使用 NewtosoftJson 而不是内置在 System.Text.Json 中。

    services.AddRazorPages().AddNewtonsoftJson(option =>
                {
                    option.SerializerSettings.Converters.Add(new StringEnumConverter());
                    option.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                });
    

    我还将属性应用于枚举 [JsonConverter(typeof(StringEnumConverter))]

    [JsonConverter(typeof(StringEnumConverter))]
    public enum Operation
    {
        [EnumMember(Value = "None")]
        None,
        [EnumMember(Value = "Send e-mail")]
        SendEmail,
        [EnumMember(Value = "Download file")]
        DownloadFile
    }
    

    现在我的页面上出现了枚举字符串值。

    deserialize json with array of enum

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 2018-08-28
      • 2020-07-15
      • 2021-04-09
      • 2020-11-09
      • 2021-01-05
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多