I am using JsonForm to produce dynamic forms in my MVC core web application. I am using System.Text.Json.JsonSerializer.Serialize
in the following code in my view model to produce a simple one field form. My aim is to store this json in the database eventually and retrieve it from there.
public TestsViewModel GetFormControls1()
{
var myJsonModel = new
{
schema = new
{
client = new
{
type = "object",
title = "Client",
properties = new
{
forename = new
{
type = "string",
title = "Forename",
minLength = 3,
maxLength = 10,
}
}
}
},
form = new List<Object>
{
new {
key = "client.forename",
title = "Forename"
}
},
value = new
{
client = new
{
forename = "",
}
}
};
TestsViewModel homeVm = new TestsViewModel();
homeVm.FormControls = System.Text.Json.JsonSerializer.Serialize(myJsonModel);
return homeVm;
}
Above code works fine and produces following json schema which is then used to create a form.
{
"schema": {
"client": {
"type": "object",
"title": "Client",
"properties": {
"forename": {
"type": "string",
"title": "Forename",
"minLength": 3,
"maxLength": 10
}
}
}
},
"form": [
{
"key": "client.forename",
"title": "Forename"
}
],
"value": {
"client": {
"forename": ""
}
}
}
I now need to produce an enum for my json so that a drop down for selecting a gender can appear in the form. However, I am unable to do that via c# code. Can someone help? I would like my c# code to produce following json (note two entries for gender in schema and form).
{
"schema": {
"client": {
"type": "object",
"title": "Client",
"properties": {
"forename": {
"type": "string",
"title": "Forename",
"minLength": 3,
"maxLength": 10
},
"gender": {
"type": "string",
"title": "Gender",
"enum": [
"male",
"female",
"alien"
]
}
}
}
},
"form": [
{
"key": "client.forename",
"title": "Forename"
},
{
"key": "client.gender",
"titleMap": {
"male": "Dude",
"female": "Dudette",
"alien": "I'm from outer space!"
}
}
],
"value": {
"client": {
"forename": ""
}
}
}
I have tried using following code but enum
is a keyword in c# so I get error.
gender = new
{
type = "string",
title = "Gender",
enum = "[male, female, alien]"
}
Also Enum = "[male, female, alien]"
produces "Enum": "[male, female, alien]"
instead of "enum": [ "male", "female", "alien" ]
I have a gender lookup table which I will be eventually using to produce above enum somehow so any idea regarding that would be helpful as well.
UPDATE @dbc's comment provides solution to most of my problem. However, I am still struglling with producing titleMap json if I try to map string to an int.
var gender3 = new
{
type = "string",
title = "Gender",
titleMap = new List<string> { new string("1" + ":" + "Male"), new string("2" + ":" + "Female")}
};
Above code produces
{
"type": "string",
"title": "Gender",
"titleMap": [
"1:Male",
"2:Female"
]
}
However, I need both 1 and Male in their own double quotations inside { } instead of [ ] as shown below.
{
"type": "string",
"title": "Gender",
"titleMap": {
"1": "Male",
"2": "Female"
}
}