I have a Razor page and on that page I show data in a JavaScript datatable. I tried to show enum value as a string, but I don't get the correct string representation for my enum value.
Startup.cs
services.AddRazorPages().AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
Enums.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; }
}
ResultPage
public IActionResult OnPost()
{
var resultData = _dbContext.Results.ToList();
var jsonData = new {recordsTotal = resultData.Count(), data = resultData
};
return new JsonResult(jsonData);
}
ResultView Here is just script for JS datatable
<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>
When I call this I get the correct enum representation from the EnumMember value:
var test = JsonConvert.SerializeObject(resultData); //SendEmail -> "Send e-mail"
But, when I:
return new JsonResult(resultData); //SendEmail -> "SendEMail"
I tried with this solution ASP.NET MVC Core API Serialize Enums to String but I don't get the expected results.