[英]Enum value doesn't show EnumMember value on razor page ASP.NET Core 3.1
我有一個 Razor 頁面,在該頁面上我在 JavaScript 數據表中顯示數據。 我試圖將枚舉值顯示為字符串,但我沒有得到我的枚舉值的正確字符串表示。
啟動文件
services.AddRazorPages().AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
枚舉文件
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Operation
{
[EnumMember(Value = "None")]
None,
[EnumMember(Value = "Send e-mail")]
SendEmail,
[EnumMember(Value = "Download file")]
DownloadFile
}
結果.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);
}
ResultView這里只是 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但我沒有得到預期的結果。
經過 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
}
現在我在我的頁面上期望 enum 字符串值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.